当我执行此操作时:
declare @INP_ITBL_NM_SQL char (64)
Exec('
select '+@INP_ITBL_NM_SQL+' =
concat(LTRIM(RTRIM(a.db_schema_name)),LTRIM(RTRIM(b.Name)))
from '+@db_and_schema+' as a, '+@split_itbl+' as b
where b.ID = 2 and a.libname = (select c.Name from
'+@split_itbl+' as c where c.ID = 1)
')
我收到以下错误:
信息102,级别15,状态1,第2行在'='附近的语法不正确。
select语句中的变量是临时表,每次运行时都需要更改其名称。
感谢您的帮助!
答案 0 :(得分:1)
您收到该错误,是因为您试图将本地变量的值设置为动态SQL中的值。因此,当您打印出该SQL文本时,它看起来就像:
SELECT = concat…
应该使用带有sp_executesql的输出参数来执行此操作。类似于以下内容:
DECLARE @SQL nvarchar(max)
DECLARE @ParamDef nvarchar(200)
DECLARE @INP_ITBL_NM_SQL varchar(100) = ''
SET @ParamDef = N'@INP_ITBL_NM_SQL_OUTPUT varchar(100) OUTPUT';
SET @SQL = N'select @INP_ITBL_NM_SQL_OUTPUT = concat(LTRIM(RTRIM(a.db_schema_name)),LTRIM(RTRIM(b.Name)))
from '+ @db_and_schema+ ' as a, ' + @split_itbl +' as b
where b.ID = 2 and a.libname = (select c.Name from
'+ @split_itbl +' as c where c.ID = 1)'
EXEC sp_executesql @SQL, @ParamDef, @INP_ITBL_NM_SQL_OUTPUT=@INP_ITBL_NM_SQL OUTPUT;
SELECT @INP_ITBL_NM_SQL