这是我的SQL游标的片段,它可以正常工作。但我现在想要将多个参数传递给@sql
。
请参阅第二个代码段中的评论。我用谷歌搜索了,但我似乎无法找到答案。
set @sql = N' use TESTDOMAINDATABASE' + convert(nvarchar, @domainID) + @NewLineChar +
N' select @subDomain = (select subDomain from tblDomains (nolock))'
execute sp_executesql @sql, N'@subDomain nvarchar(500) output', @subDomain output
print 'subDomain is ' + @subDomain + ' and the domainID is ' + convert(nvarchar,@domainID)
但是,我想说我想要tblDomains
中的另一列(比如domainName
)。
我如何更新上述声明?
set @sql = N' use TESTDOMAINDATABASE' + convert(nvarchar, @domainID) + @NewLineChar +
N' select @subDomain = (select subDomain from tblDomains (nolock))' + @NewLineChar +
N'select @domainName = (select domainName from tblDomains(nolock))'
execute sp_executesql @sql, N'@subDomain nvarchar(500) output', @subDomain output /* How do I pass multiple paramaters here ? */
execute sp_executesql @sql, N'@domainName nvarchar(500) output', @domainName output /*Adding a 2nd line does not do the trick - results in an error that I must declare the scalar variable @domainName */
print 'subDomain is ' + @subDomain + ' and the domainID is ' + convert(nvarchar,@domainID) + ' + and the domain name is ' @domainName'
答案 0 :(得分:2)
set @sql = N' use TESTDOMAINDATABASE' + convert(nvarchar, @domainID) + @NewLineChar +
N' select @subDomain = subDomain, @domainName = domainName
from tblDomains (nolock);'
execute sp_executesql @sql,
N'@subDomain nvarchar(500) output, @domainName nvarchar(500) output',
@subDomain output, @domainName output;
print 'subDomain is ' + @subDomain + ' and the domainID is ' + convert(nvarchar,@domainID)
答案 1 :(得分:1)
您可以将多个以逗号分隔的参数传递给sp_executesql。
DECLARE @sql nvarchar(MAX)
DECLARE @x nvarchar(25)
DECLARE @y nvarchar(25)
SET @sql = N'SELECT @x = ''hello'', @y = ''world'''
execute sp_executesql @sql, N'@x nvarchar(25) output, @y nvarchar(25) output'
,@x output
,@y output
PRINT @x + ' ' + @y