“筑巢”动态 SQL 中的变量 - 如何保持有效的语法?

发布于 2024-11-27 18:46:30 字数 1079 浏览 0 评论 0原文

如果有人问这个问题,我很抱歉,而且我太笨了,无法找到答案。

我试图确定执行以下操作的最佳方法:

Declare @sql nvarchar(4000)
, @Filter nvarchar(500)

SET @filter = 'WHERE value1 IN (''A'',''B'',''C'')'

SET @sql = '
DECLARE @Field nvarchar(50)

DECLARE process CURSOR FOR
SELECT value2
FROM table
'+@filter+'

OPEN process

FETCH NEXT FROM process
INTO @field

WHILE @@Fetch_Status = 0
BEGIN

EXEC stored_procedure
@field = @field
@filter = '+@filter+'

FETCH NEXT FROM process
INTO @field

END

CLOSE process
DEALLOCATE process
' print @sql execute sp_executesql @sql

这里的问题是它转换为

DECLARE @Field nvarchar(50)

DECLARE process CURSOR FOR
SELECT value2
FROM table
WHERE value1 IN ('A','B','C')

OPEN process

FETCH NEXT FROM process
INTO @field

WHILE @@Fetch_Status = 0
BEGIN

EXEC stored_procedure
@field = 'N'
@filter = 'WHERE value1 IN ('A','B','C')'

FETCH NEXT FROM process
INTO @field

END

CLOSE process
DEALLOCATE process

当然,这会导致 A、B 和 C 处出现语法错误

我尝试了 replace( 的多种变体@filter,','') 来纠正这个问题,但这似乎对我没有任何好处。

请问有什么想法吗?

I apologize if this has been asked and I am to dense to grok the answer.

I am trying to determine the best way to do the following:

Declare @sql nvarchar(4000)
, @Filter nvarchar(500)

SET @filter = 'WHERE value1 IN (''A'',''B'',''C'')'

SET @sql = '
DECLARE @Field nvarchar(50)

DECLARE process CURSOR FOR
SELECT value2
FROM table
'+@filter+'

OPEN process

FETCH NEXT FROM process
INTO @field

WHILE @@Fetch_Status = 0
BEGIN

EXEC stored_procedure
@field = @field
@filter = '+@filter+'

FETCH NEXT FROM process
INTO @field

END

CLOSE process
DEALLOCATE process
' print @sql execute sp_executesql @sql

The problem here is that it translates to

DECLARE @Field nvarchar(50)

DECLARE process CURSOR FOR
SELECT value2
FROM table
WHERE value1 IN ('A','B','C')

OPEN process

FETCH NEXT FROM process
INTO @field

WHILE @@Fetch_Status = 0
BEGIN

EXEC stored_procedure
@field = 'N'
@filter = 'WHERE value1 IN ('A','B','C')'

FETCH NEXT FROM process
INTO @field

END

CLOSE process
DEALLOCATE process

Of course in this leads to a syntax error at A, B, and C

I have tried a number of variations of replace(@filter,','') to correct this, but this doesn't seem to do me any good.

Ideas please?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤星 2024-12-04 18:46:30

使用:

replace(@filter,'''','''''')

Use:

replace(@filter,'''','''''')
方圜几里 2024-12-04 18:46:30

改变这部分

…
EXEC stored_procedure
@field = @field
@filter = '+@filter+'
…

像这样

…
EXEC stored_procedure
@field = @field
@filter = '''+REPLACE(@filter, '''', '''''')+'''

Change this part

…
EXEC stored_procedure
@field = @field
@filter = '+@filter+'
…

like this

…
EXEC stored_procedure
@field = @field
@filter = '''+REPLACE(@filter, '''', '''''')+'''
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文