如何从不同的表格中选择

时间:2022-11-12 17:09:08

I have some tables with different data, but them have the same column UserId:

我有一些表有不同的数据,但它们具有相同的列UserId:

If you declare like that :

如果你这样声明:

declare @Type nvarchar(max) = 'Video';
declare @Id nvarchar(max)='M00000000007199';
declare @UserIdTable TABLE (UserId bigint)

Then I want to insert value into @UserIdTable by @Type, and I imaged :

然后我想通过@Type将值插入@UserIdTable,然后我成像:

insert into @UserIdTable 
case when @Type=Video then
  select UserId from VideoTable
else
  select UserId from TvTable
end

I know that is wrong, what should I do for this problem?

我知道这是错的,我应该为这个问题做些什么?

1 个解决方案

#1


3  

CASE in T-SQL is an expression which can return a value - it is not a flow control statement like in C# or VB.NET, and it cannot contain SQL statements or code blocks.

T-SQL中的CASE是一个可以返回值的表达式 - 它不是像C#或VB.NET中那样的流控制语句,它不能包含SQL语句或代码块。

You'll need to rewrite your code to use a regular IF .. THEN ... ELSE statement - something like this:

您需要重写代码以使用常规IF .. THEN ... ELSE语句 - 类似这样的内容:

IF @Type = Video 
   INSERT INTO @UserIdTable 
      SELECT UserId FROM dbo.VideoTable
ELSE
   INSERT INTO @UserIdTable 
      SELECT UserId FROM dbo.TvTable

#1


3  

CASE in T-SQL is an expression which can return a value - it is not a flow control statement like in C# or VB.NET, and it cannot contain SQL statements or code blocks.

T-SQL中的CASE是一个可以返回值的表达式 - 它不是像C#或VB.NET中那样的流控制语句,它不能包含SQL语句或代码块。

You'll need to rewrite your code to use a regular IF .. THEN ... ELSE statement - something like this:

您需要重写代码以使用常规IF .. THEN ... ELSE语句 - 类似这样的内容:

IF @Type = Video 
   INSERT INTO @UserIdTable 
      SELECT UserId FROM dbo.VideoTable
ELSE
   INSERT INTO @UserIdTable 
      SELECT UserId FROM dbo.TvTable