SQL Server:根据变量

时间:2018-06-10 20:18:43

标签: sql sql-server

我的查询看起来很像:

 DECLARE @Vendor varchar (50)
--SET @Vendor = 55 --One vendor
--Set @Vendor = 234 --Another vendor
--SET @Vendor = 123 --Another vendor

SELECT column1, column2, column3
FROM [dbo].[TABLE1]
WHERE vendor_key = @Vendor
  AND create_date > CONVERT(VARCHAR, GETDATE(), 112)
ORDER BY column1;

SELECT column1, column2, column3
FROM [dbo].[TABLE2]
WHERE vendor_key = @Vendor
  AND create_date > CONVERT(VARCHAR, GETDATE(), 112)
ORDER BY column1;

我通过取消注释我需要信息的任何供应商来循环显示已注释掉的供应商编号列表。 (这是一个比上面列出的3更长的列表。这让我可以为所有供应商使用一个查询,而无需记住供应商数量)。

唯一的烦恼是同一台服务器上有很多不同的数据库,根据供应商的不同,我需要从下拉列表中手动选择正确的数据库。

理想情况下,我想编写某种IF语句,它将设置数据库名称,或者替换表名前面的“[dbo]”,具体取决于上面设置的供应商编号。

所以,

IF @Vendor = 55 
   SET @database = "Vendor1DB", 
ELSE IF @Vendor = 234 
   SET @database = "Vendor2DB" (and so on)

这可能吗?

1 个答案:

答案 0 :(得分:0)

动态SQL是一种方法:

DECLARE @vendor int = 55;
DECLARE @DatabaseName sysname;
DECLARE @SqlScript nvarchar(MAX);

SELECT @DatabaseName =
    CASE @vendor
        WHEN 55 THEN  'OneVendor'
        WHEN 234 THEN 'AnotherVendor'
        WHEN 123 THEN 'YetAnotherVendor'
    END;
IF @DatabaseName IS NULL
    RAISERROR( 'Unknown vendor (%d) specified', 16, 1, @vendor);
SET @SqlScript = N'USE ' + QUOTENAME(@DatabaseName) + N';
SELECT column1, column2, column3
FROM [dbo].[TABLE1]
WHERE vendor_key = @Vendor
  AND create_date > CONVERT(VARCHAR, GETDATE(), 112)
ORDER BY column1;

SELECT column1, column2, column3
FROM [dbo].[TABLE2]
WHERE vendor_key = @Vendor
  AND create_date > CONVERT(VARCHAR, GETDATE(), 112)
ORDER BY column1;
';
EXECUTE sp_executesql 
      @SqlScript
    , N'@Vendor varchar(50)'
    , @vendor=@vendor;
GO

另一个是在SQLCMD模式下从SSMS运行SQLCMD脚本(查询 - > SQLCMD模式)。不幸的是,没有一种简单的方法可以动态设置SQLCMD变量。下面的示例使用T-SQL使用the technique described here生成并执行所需的SETVAR命令。

--redirect STDOUT to file
:out d:\temp\UseStatement.sql
GO

--generate file with :SETVAR DatabaseName
DECLARE @vendor int = 55;
DECLARE @SetVarCommand nvarchar(200);
SELECT @SetVarCommand =
    CASE @vendor
        WHEN 55 THEN  ':SETVAR DatabaseName OneVendor;'
        WHEN 234 THEN ':SETVAR DatabaseName AnotherVendor;'
        WHEN 123 THEN ':SETVAR DatabaseName YetAnotherVendor;'
    END;
IF @SetVarCommand IS NULL
    RAISERROR( 'Unknown vendor (%d) specified', 16, 1, @vendor);
PRINT @SetVarCommand;
GO

--redirect STDOUT to default
:out stdout
GO

--execute SETVAR script for DatabaseName
:r d:\temp\UseStatement.sql
GO
--specify $(DatabaseName) in your sql script where the database name is needed
USE $(DatabaseName);
SELECT column1, column2, column3
FROM [dbo].[TABLE1]
WHERE vendor_key = @Vendor
  AND create_date > CONVERT(VARCHAR, GETDATE(), 112)
ORDER BY column1;

SELECT column1, column2, column3
FROM [dbo].[TABLE2]
WHERE vendor_key = @Vendor
  AND create_date > CONVERT(VARCHAR, GETDATE(), 112)
ORDER BY column1;
GO