T-SQL相当于C ++ #define

时间:2019-07-15 12:51:12

标签: sql-server

我有一个SQL脚本,可一次更改多个视图的源表。为此,我希望拥有类似的东西

#define source theSourceTable

而不是查找和替换我需要的零件。我的理解是,使用局部变量是不可能的,但是还有另一种方法吗?

2 个答案:

答案 0 :(得分:3)

就像我在评论中提到的SYNONYM在这里似乎是正确的主意。由于我们的工作量很少,下面是一个过于简化的示例:

USE Sandbox;
GO
--Create some sample tables
CREATE TABLE dbo.MyTable1 (MyColumn int);
INSERT INTO dbo.MyTable1 (MyColumn)
VALUES (1),(2);

CREATE TABLE dbo.MyTable2 (MyColumn int);
INSERT INTO dbo.MyTable2 (MyColumn)
VALUES (3),(4);
GO
--Create synonyms
CREATE SYNONYM dbo.MyTableA FOR dbo.MyTable1;
CREATE SYNONYM dbo.MyTableB FOR dbo.MyTable1;
GO
--Create views
CREATE VIEW MyView1 AS
    SELECT MyColumn, 'View1' AS ObjectName
    FROM dbo.MyTableA;
GO

CREATE VIEW MyView2 AS
    SELECT MyColumn, 'View2' AS ObjectName
    FROM dbo.MyTableB;
GO

CREATE VIEW MyView3 AS
    SELECT A.MyColumn AS AColumn,
          B.MyColumn AS BColumn,
          'View3' AS ObjectName
    FROM dbo.MyTableA A
         CROSS JOIN dbo.MyTableB B;
GO
--Check data
SELECT *
FROM dbo.MyView1;
SELECT *
FROM dbo.MyView2;
SELECT *
FROM dbo.MyView3;
GO
--Create a new table
CREATE TABLE dbo.MyTable3 (MyColumn int);
INSERT INTO dbo.MyTable3 (MyColumn)
VALUES (5),(6);
GO
--Alter the synonyms
DROP SYNONYM dbo.MyTableA;
CREATE SYNONYM dbo.MyTableA FOR dbo.MyTable2;
DROP SYNONYM dbo.MyTableB;
CREATE SYNONYM dbo.MyTableB FOR dbo.MyTable3;
GO
--Check views again:
--Check data
SELECT *
FROM dbo.MyView1;
SELECT *
FROM dbo.MyView2;
SELECT *
FROM dbo.MyView3;
GO
--Clean up
DROP VIEW dbo.MyView1;
DROP VIEW dbo.MyView2;
DROP VIEW dbo.MyView3;
DROP SYNONYM dbo.MyTableA;
DROP SYNONYM dbo.MyTableB;
DROP TABLE dbo.MyTable1;
DROP TABLE dbo.MyTable2;
DROP TABLE dbo.MyTable3;

您将需要编辑所有视图的现有DDL一次,以改用新的同义词名称,但是之后您可以简单地重新创建同义词即可将它们全部更新。

答案 1 :(得分:0)

您也许可以使用SQLCMD模式(用ALT-Q-M激活或在SSMS的“查询”菜单中切换它)。

:SETVAR MyTable SomeTableName

CREATE OR ALTER VIEW dbo.myView
AS

SELECT * FROM dbo.$(MyTable)
GO

最后将得到一个从SomeTableName中选择*的视图

或者,您可以使用动态sql

DECLARE @sql VARCHAR(MAX)
DECLARE @myTable VARCHAR(100) = 'SomeTableName'

SET @sql = 'CREATE OR ALTER VIEW dbo.myView
AS

SELECT * FROM dbo.' + @myTable

EXEC(@sql)

具有相同的最终结果。

(CREATE OR ALTER是SQL2016语法糖,如果您使用的是旧版本,请进行相应调整)