我最终使用DDL触发器将更改从一个表复制到另一个表。唯一的问题是,如果一个表或列名包含一个保留字的一部分(varchar的arch),它将导致修改脚本出现问题。
再次感谢
Brent Ozar
在我之前检查我的想法
blogged them
.
-- Create pvt and pvtWeb as test tables
CREATE TABLE [dbo].[pvt](
[VendorID] [int] NULL,
[Emp1] [int] NULL,
[Emp2] [int] NULL,
[Emp3] [int] NULL,
[Emp4] [int] NULL,
[Emp5] [int] NULL
) ON [PRIMARY];
GO
CREATE TABLE [dbo].[pvtWeb](
[VendorID] [int] NULL,
[Emp1] [int] NULL,
[Emp2] [int] NULL,
[Emp3] [int] NULL,
[Emp4] [int] NULL,
[Emp5] [int] NULL
) ON [PRIMARY];
GO
IF EXISTS(SELECT * FROM sys.triggers WHERE name = âddl_trigger_pvt_alterâ)
DROP TRIGGER ddl_trigger_pvt_alter ON DATABASE;
GO
-- Create a trigger that will trap ALTER TABLE events
CREATE TRIGGER ddl_trigger_pvt_alter
ON DATABASE
FOR ALTER_TABLE
AS
DECLARE @data XML;
DECLARE @tableName NVARCHAR(255);
DECLARE @newTableName NVARCHAR(255);
DECLARE @sql NVARCHAR(MAX);
SET @sql = â;
-- Store the event in an XML variable
SET @data = EVENTDATA();
-- Get the name of the table that is being modified
SELECT @tableName = @data.value(â(/EVENT_INSTANCE/ObjectName)[1]â, âNVARCHAR(255)â);
-- Get the actual SQL that was executed
SELECT @sql = @data.value(â(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]â, âNVARCHAR(MAX)â);
-- Figure out the name of the new table
SET @newTableName = @tableName + âWebâ;
-- Replace the original table name with the new table name
-- str_replace is from Robyn Page and Phil Factorâs delighful post on
-- string arrays in SQL. The other posts on string functions are indispensible
-- to handling string input
--
-- http://www.simple-talk.com/sql/t-sql-programming/tsql-string-array-workbench/
-- http://www.simple-talk.com/sql/t-sql-programming/sql-string-user-function-workbench-part-1/
--http://www.simple-talk.com/sql/t-sql-programming/sql-string-user-function-workbench-part-2/
SET @sql = dbo.str_replace(@tableName, @newTableName, @sql);
-- Debug the SQL if needed.
--PRINT @sql;
IF OBJECT_ID(@newTableName, NâUâ) IS NOT NULL
BEGIN
BEGIN TRY
-- Now that the table name has been changed, execute the new SQL
EXEC sp_executesql @sql;
END TRY
BEGIN CATCH
-- Rollback any existing transactions and report the full nasty
-- error back to the user.
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
DECLARE
@ERROR_SEVERITY INT,
@ERROR_STATE INT,
@ERROR_NUMBER INT,
@ERROR_LINE INT,
@ERROR_MESSAGE NVARCHAR(4000);
SELECT
@ERROR_SEVERITY = ERROR_SEVERITY(),
@ERROR_STATE = ERROR_STATE(),
@ERROR_NUMBER = ERROR_NUMBER(),
@ERROR_LINE = ERROR_LINE(),
@ERROR_MESSAGE = ERROR_MESSAGE();
RAISERROR(âMsg %d, Line %d, :%sâ,
@ERROR_SEVERITY,
@ERROR_STATE,
@ERROR_NUMBER,
@ERROR_LINE,
@ERROR_MESSAGE);
END CATCH
END
GO
ALTER TABLE pvt
ADD test INT NULL;
GO
EXEC sp_help pvt;
GO
ALTER TABLE pvt
DROP COLUMN test;
GO
EXEC sp_help pvt;
GO