使用数据库名称定义SQL变量

时间:2014-05-24 12:33:00

标签: sql sql-server variables

使用此T-SQL查询,我定义了一个带有日期的变量@InDate

SET 
    @InDate = (SELECT MIN(bt.CreateDate) AS [INDATE]
               FROM  
                   mydatabase.dbo.BuyTransaction bt
               LEFT JOIN 
                   mydatabase.dbo.TransactionExtraFields tef ON bt.TransDocument = tef.TransDocument 
                                                             AND bt.TransSerial = tef.TransSerial 
                                                             AND bt.TransDocNumber = tef.TransDocNumber 
                                                             AND ExtraFieldID = 1
               WHERE 
                   bt.TransDocument = 'FRM' AND tef.TextAnswer = @NumPI 
                   AND bt.TransStatus = 0)

但现在我需要用另一个变量更改数据库名称。我尝试这样的东西,在一个将要执行的变量中创建一个字符串

SET @InDate = '(SELECT MIN(bt.CreateDate) AS [INDATE]
FROM mydatabase.dbo.BuyTransaction bt
LEFT JOIN mydatabase.dbo.TransactionExtraFields tef ON bt.TransDocument = tef.TransDocument AND bt.TransSerial = tef.TransSerial AND bt.TransDocNumber = tef.TransDocNumber AND ExtraFieldID = 1
WHERE bt.TransDocument = ''FRM'' AND tef.TextAnswer = '''+@NumPI+''' AND bt.TransStatus = 0)'

EXECUTE @InDate

但我的问题是如何将执行结果再次变为变量。像SET @InDate2 = EXECUTE @InDate这样的东西不起作用......

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

使用sp_executesql。我认为你的案例中的语法类似于:

declare @InDate date;
declare @sql nvarchar(max);

set @sql = N'SELECT @InDate = MIN(bt.CreateDate)
FROM mydatabase.dbo.BuyTransaction bt
LEFT JOIN mydatabase.dbo.TransactionExtraFields tef ON bt.TransDocument = tef.TransDocument AND bt.TransSerial = tef.TransSerial AND bt.TransDocNumber = tef.TransDocNumber AND ExtraFieldID = 1
WHERE bt.TransDocument = ''FRM'' AND tef.TextAnswer = '''+@NumPI+''' AND bt.TransStatus = 0';

exec sp_executesql @sql, N'@InDate date output', @InDate = @InDate output;

您也可以将@NumPI作为参数。

sp_executesql的文档是here

答案 1 :(得分:0)

我已经完成了这类问题。

请检查示例代码。它为我工作。请改变。

DECLARE @SQLString NVARCHAR(500)
    DECLARE @ParmDefinition NVARCHAR(500)
    DECLARE @IntVariable INT    
    DECLARE @Lastlname varchar(30) = 'col10 '  -- this variable use for input in sp


    SET @SQLString = N'SELECT @LastlnameOUT = '+@Lastlname+'
                       FROM TempStoreExcelData '
    SET @ParmDefinition = N'@level tinyint,
                            @LastlnameOUT varchar(30) OUTPUT'
    SET @IntVariable = 35
    EXECUTE sp_executesql
        @SQLString,
        @ParmDefinition,
        @level = @IntVariable,
        @LastlnameOUT=@Lastlname OUTPUT
    SELECT @output = @Lastlname
select @output