0

This is a snippet of my SQL cursor, which works fine. But I now want to pass multiple parameters to @sql.

See the comment in the 2nd code snippet. I've googled, but I can't seem to find the answer to this.

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)

But let's say I wanted another column from tblDomains (say domainName).

How would I update the above statement?

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テーブルに1つの行しかありませんか?

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 に答える