从CASE语句分配给T-SQL变量

我想在查询中分配一些变量,这些变量对它的列使用CASE语句.不太确定如何做到这一点,无法找到正确的语法.

这是我到目前为止,但它有语法错误.

-- set @theID and @theName with their appropriate values
 select top (1) 
 @theID = (Case when B.ID IS NULL then A.ID else B.ID END),@theName = (Case when B.Name IS NULL then A.Name else B.Name END) 
 from B left join A on A.ID = B.ID where ...

将这些变量粘贴在那里的正确位置/方法是什么?

解决方法

你给出的例子应该有效.您可以从案例陈述中分配变量.只是假装整个CASE..WHEN..THEN..ELSE..END块是一个字段.这是一个通用的例子:
declare
  @string1 nvarchar(100) = null,@string2 nvarchar(100) = null
 ;

select top 1
  @string1 = case when 1=1 then 'yes' else 'no' end,@string2 = case when 1=0 then 'yes' else 'no' end

print 'string1 = ' + @string1
print 'string2 = ' + @string2

得到:

string1 = yes
string2 = no

你能告诉我们你得到的具体错误吗?

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...