0

这是我的 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'
4

2 回答 2

2

你的意思是这样吗?每个数据库的 tblDomains 表中是否只有一行?

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)
于 2012-05-24T17:23:57.600 回答
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
于 2012-05-24T17:23:47.050 回答