动态设置表结构方案(二)

承接(一)
 
 
 
 
 
 
 
 
CREATE TRIGGER [dbo].[trgUpd]
   ON  [dbo].[bigtable]
   AFTER UPDATE
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for trigger here
	SELECT * INTO #inserted FROM INSERTED;
	SELECT * INTO #deleted FROM DELETED;

	DECLARE @sql VARCHAR(MAX) = '';

	--删除旧纪录
	SET @sql = 'DELETE FROM [bigtable.tmp] WHERE Id IN(SELECT Id FROM #deleted)';
	EXEC(@sql);

	--插入新纪录
	DECLARE @cols VARCHAR(MAX) = '';
	SELECT
		@cols = @cols + ',' + C.name
	FROM sys.columns C
	WHERE C.[object_id] = OBJECT_ID('[bigtable]');
	SET @cols = SUBSTRING(@cols,2,LEN(@cols) - 1);

	SET IDENTITY_INSERT [bigtable.tmp] ON;

	SET @sql = 'INSERT INTO [bigtable.tmp](' + @cols + ') SELECT ' + @cols + ' FROM #inserted';
	EXEC(@sql);

	SET IDENTITY_INSERT [bigtable.tmp] OFF;
END

GO

CREATE TRIGGER [dbo].[trgDel]
   ON  [dbo].[bigtable]
   AFTER DELETE
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for trigger here
	SELECT * INTO #deleted FROM DELETED;

	DECLARE @sql VARCHAR(MAX) = '';

	--删除旧纪录
	SET @sql = 'DELETE FROM [bigtable.tmp] WHERE Id IN(SELECT Id FROM #deleted)';
	EXEC(@sql);

END

GO

换表名:
exec sp_rename '旧表名','新表名'

你可能感兴趣的:(动态设置表结构方案(二))