我正试图将一个字符串附加到存储过程中的一个列值。
这是我的语法
DECLARE @Newstring VARCHAR(MAX) = 'sample';
....
IF cond1
BEGIN
SET @query = 'select
e.id, c.address,
case when a.lastname is null then a.firstname
else a.lastname + ' + @Newstring + '
end name,
.........'
我收到一个错误
列名"sample"无效
如果我将其作为查询执行,则以下串联可以使用
select
e.id, c.address,
case
when a.lastname is null then a.firstname
else a.lastname + 'sample'
end name,
但是我不能在存储过程中使用相同的语法,或者不能使用声明的变量。我也没有在网上找到任何解决方案。
欢迎提出任何建议。
您需要给它一个数据类型。。。如CCD_ 1。更改为:
Declare @Newstring varchar(64) = 'sample';
并确保64足够大,可以容纳你正在传递的东西。如果没有,请使用更大的东西。此外,如果要传入unicode,则可能需要NVARCHAR
。
此外,动态字符串缺少一个结束引号,BEGIN
缺少一个END
,需要添加引号以使值成为文字。
Declare @Newstring varchar(20) = 'sample'
declare @query varchar(max)
IF 1=1
BEGIN
set @query = '
select e.id, c.address,
case when a.lastname is null then a.firstname
else a.lastname + ''' + @Newstring + ''' --added quotes to make the string a literal during execution
end name' ---quote added here
END --added END here
print @query
列名"sample"无效
您的查询将生成如下所示。由于示例不是列名,它将抛出上述错误。
select
e.id, c.address,
case
when a.lastname is null then a.firstname
else a.lastname + sample
end name
修改您的查询以包含参数周围的引号
set @query = '
select e.id, c.address,
case when a.lastname is null then a.firstname
else a.lastname + ''' + @Newstring + '''
end name'