设置语句在sql查询中的if子句中不起作用

时间:2013-07-03 10:09:42

标签: sql if-statement sql-server-2008-r2 set syntax-error

这是一个简单的查询,花了很多时间,但我仍然无法得到这个。

我遇到问题,如果条件为真,我需要设置一个局部变量。

 Declare @asdf as nvarchar (max)
Declare @nm as nvarchar(30);
select @nm = (Select name from Core.[Lookup] where Id = 1)
Declare @dfdf as nvarchar (max)

if @nm is not null
select @asdf + 'sadf'
endif

select @nm = (Select name from Core.[Lookup] where Id = 15)
if @nm is not null
select @asdf + 'asdff'
endif

以上工作正常。但是,如果我将select语句更改为set语句,我会收到错误。 'endif'附近的语法不正确。

Declare @asdf as nvarchar (max)
Declare @nm as nvarchar(30);
select @nm = (Select name from Core.[Lookup] where Id = 1)
Declare @dfdf as nvarchar (max)

if @nm is not null
set @asdf = 'sadf'
endif

select @nm = (Select name from Core.[Lookup] where Id = 15)
if @nm is not null
set @asdf = 'asdff'
endif

由于

1 个答案:

答案 0 :(得分:2)

endif中没有T-SQL个关键字,正确的查询如下:

Declare @asdf as nvarchar (max)
Declare @nm as nvarchar(30);
select @nm = (Select name from Core.[Lookup] where Id = 1)
Declare @dfdf as nvarchar (max)

if @nm is not null
begin
     set @asdf = 'sadf'
end

select @nm = (Select name from Core.[Lookup] where Id = 15)
if @nm is not null
begin
   set @asdf = 'asdff'
end