15

OK, so I've got this line of code in a search stored procedure:

SET @where = 'job_code = ''' + REPLACE(@job_code, '''', '''''') + ''''

and there are basically two operations I'd like to streamline -the first being surrounding the concatenated value in single quotes. Obviously, in the above statement, I'm escaping a ' by using two '' and then ending the string with a ' so I can concatenate the actual value. There's got to be a better way!

The second of the operations would be the REPLACE(@job_code, '''', '''''') where I'm escaping any single quotes that might exist in the field.

Isn't there a much more elegant way of writing this line of code as a whole?

I thought it was the ESCAPE keyword but that's tied tightly to the LIKE statement, so no go there.

4

4 回答 4

28

不确定如何执行 sql 查询,如果使用 sp_executesql,可能是这样的

EXECUTE sp_executesql 
          N'SELECT * FROM YouTable WHERE job_code = @job_code',
          N'@job_code varchar(100)',
          @job_code = @job_code;
于 2013-04-30T20:28:44.543 回答
6

参数化查询答案可能是真正的“正确答案”,但要回答您的原始问题,您想要的是QUOTENAME()。更具体地说,单引号版本:

SET @where = 'job_code = ' + QUOTENAME(@job_code, '''')

但是请注意这里的长度限制(输入是 a sysname,意思是 128 个字符),因为它旨在引用数据库对象的名称,而不是作为通用机制。

于 2013-05-03T19:15:43.410 回答
2

您可以定义一个处理典型场景的函数,例如:

create function WrapAndReplaceQuotes (@input as varchar(max))
returns varchar(max)
as
begin
    return '''' + replace(@input, '''', '''''') + ''''
end

SET @where = 'job_code = ' + WrapAndReplaceQuotes(@job_code)
于 2013-04-30T20:27:20.053 回答
2

您可以声明常量:

declare @SQ as char(1) = ''''

SET @where = 'job_code = ' + @SQ + REPLACE(@job_code, @SQ, @SQ + @SQ) + @SQ
于 2013-04-30T20:22:36.160 回答