当前位置: 代码迷 >> Sql Server >> 动态SQL语法异常
  详细解决方案

动态SQL语法异常

热度:68   发布时间:2016-04-24 10:45:36.0
动态SQL语法错误

DECLARE @accountId nvarchar(36),@accountList nvarchar(4000),@accountType int
SET @accountId='2ef51e92-931e-4cbc-8d0c-9502cc2fa32b'
SET @accountType= 1
SET @accountList=''
SELECT @accountList = @accountList +''''+ Id + ''',' FROM tb_Account
SET @accountList = left(@accountList,len(@accountList)-1)

--这句不会报错
--exec('select * from tb_Account where 1=1 and Id in ('+@accountList+')')

--这句就要报错:消息 102,级别 15,状态 1,第 1 行 ',' 附近有语法错误。
exec('select * from tb_Account where Id in (CASE WHEN '+@accountType+'=1 THEN '+@accountList+' ELSE N'''+@accountId+''' END)')



------解决方案--------------------
最后一句改成这个:
print('select * from tb_Account where Id in (CASE WHEN '+@accountType+'=1 THEN '+@accountList+' ELSE N'''+@accountId+''' END)')

贴结果
------解决方案--------------------
引用:
Quote: 引用:

最后一句改成这个:
print('select * from tb_Account where Id in (CASE WHEN '+@accountType+'=1 THEN '+@accountList+' ELSE N'''+@accountId+''' END)')

贴结果


消息 245,级别 16,状态 1,第 10 行
在将 varchar 值 'select * from tb_Account where Id in (CASE WHEN ' 转换成数据类型 int 时失败。


exec('select * from tb_Account where Id in (CASE WHEN '+cast(@accountType as varchar(20))+'=1 THEN '+@accountList+' ELSE N'''+@accountId+''' END)')


------解决方案--------------------

select a.* 
from tb_Account a
join tb_Account b on a.id = case @accountType when 1 then b.id else @accountId end

换成join 吧
------解决方案--------------------
exec('select * from tb_Account where ('+cast(@accountType as varchar(20))+'=1 and id in ('+@accountList+')) 
or ('+cast(@accountType as varchar(20))+'<>1 and id in ('+@accountId+'))
  相关解决方案