常量查询存储过程

时间:2011-01-05 11:17:18

标签: sql-server stored-procedures

这是SQL Server存储过程的代码。我已声明常量@other_db在查询中使用它。对于简单的查询,我可以按照下面的说明进行操作。

DECLARE @other_db VARCHAR(50)

    SET @other_db = 'BABMwork8_22_1210_0012'

    UPDATE BABMwork8_22_1210_0012.dbo.concessions   SET double_ones = '' WHERE double_ones = 'Yes'  

    EXEC('UPDATE @other_db.dbo.concessions SET double_ones = '+''+' WHERE double_ones = '+'Yes')

但是对于下面提到的查询,我想使用常量@other_db来替换BABMwork8_22_1210_0012的值。

UPDATE concessions SET double_ones = 'Yes'
                   WHERE (concession IN(SELECT concession FROM BABMwork8_22_1210_0012.dbo.concessions WHERE
                                        (manuell_archive_delete! = 'Delete' OR  manuell_archive_delete IS NULL) AND 
                                        (double_action = 'ok_invoice' OR double_action is NULL)) 
                          OR concession IN(SELECT Concession FROM BABMwork8_22_1210_0012.dbo.invoicing WHERE 
                                        (can_invoiced is NULL OR can_invoiced != 'No') AND
                                        (double_action = 'ok_invoice' OR double_action is NULL)))
                          AND (double_action = 'ok_invoice' OR double_action is NULL) 
                          AND (manuell_archive_delete! = 'Delete' OR  manuell_archive_delete IS NULL) AND
                               source!= 'PARK'

尽管我尝试使用EXEC,但它变得越来越复杂。如果有任何简单的方法可以使用常量,我有几个查询。

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

好的,有几种方法可以做到这一点。

您可以在开始时定义和填充临时表,并使用动态exec查询结果填充它。然后在你编写的t-sql中,只需用临时表名替换BABMwork8_22_1210_0012。

样品:

CREATE TABLE #BABMworkInv 
  (col1 varchar, col2 varchar, col3 int....)

INSERT #BABMworkInv
  EXEC ('select * from ' + @other_db + '.dbo.invoicing')

UPDATE concessions SET double_ones = 'Yes'
                   WHERE (concession IN(SELECT concession FROM #BABMworkInv WHERE
                                        (manuell_archive_delete! = 'Delete' OR  manuell_archive_delete IS NULL) AND 
                                        (double_action = 'ok_invoice' OR double_action is NULL)) 
                          OR concession IN(SELECT Concession FROM #BABMworkInv WHERE 
                                        (can_invoiced is NULL OR can_invoiced != 'No') AND
                                        (double_action = 'ok_invoice' OR double_action is NULL)))
                          AND (double_action = 'ok_invoice' OR double_action is NULL) 
                          AND (manuell_archive_delete! = 'Delete' OR  manuell_archive_delete IS NULL) AND
                               source!= 'PARK'

第二种方法是创建接受数据库名称作为参数和返回表结果的函数。然后,您可以使用以下代码:Select * from dbo.MyFunction(@other_db)