1

我正在创建新数据库,并且在每个表中我希望有几列,例如:

CreatedBy, 
CreatedDate, 
ModifiedBy, 
ModifiedDate,
.... 

因此,如果有人创建表;这些列应自动添加,无需在创建表 T-SQL 中编写这些列的脚本。我从 Management Studio 通过设计创建或使用脚本它应该自动添加这些列。

有没有办法做到这一点?

4

1 回答 1

3

试试这个动态查询(自动将列添加到您的表中):

DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = STUFF((
    SELECT CHAR(13) + 'ALTER TABLE [' + SCHEMA_NAME(o.[schema_id]) + '].[' + o.name + ']
    ADD 
          CreatedBy DATETIME
        , CreatedDate DATETIME
        , ModifiedBy DATETIME
        , ModifiedDate DATETIME;'
    FROM sys.objects o
    WHERE o.[type] = 'U'
        AND NOT EXISTS(
            SELECT 1 
            FROM sys.columns c
            WHERE o.[object_id] = c.[object_id]
                AND TYPE_NAME(c.system_type_id) = 'DATETIME'
                AND c.name IN ('CreatedBy', 'CreatedDate', 'ModifiedBy', 'ModifiedDate')
        )
    FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, '')


PRINT @SQL
EXEC sys.sp_executesql @SQL

输出:

ALTER TABLE [dbo].[test]
    ADD 
          CreatedBy DATETIME
        , CreatedDate DATETIME
        , ModifiedBy DATETIME
        , ModifiedDate DATETIME;

使用 DDL 触发器更新:

CREATE TRIGGER TRG_TABLES
    ON DATABASE 
    AFTER CREATE_TABLE
AS 
BEGIN
    SET NOCOUNT ON;

    DECLARE @TABLE_NAME SYSNAME
    SELECT @TABLE_NAME = EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]', 'SYSNAME')

    DECLARE @SQL NVARCHAR(MAX)
    SELECT @SQL = STUFF((
        SELECT CHAR(13) + 'ALTER TABLE [' + SCHEMA_NAME(o.[schema_id]) + '].[' + o.name + ']
        ADD 
              CreatedBy DATETIME
            , CreatedDate DATETIME
            , ModifiedBy DATETIME
            , ModifiedDate DATETIME;'
        FROM sys.objects o
        WHERE o.[type] = 'U'
            AND o.[object_id] = OBJECT_ID(@TABLE_NAME)
            AND NOT EXISTS(
                SELECT 1 
                FROM sys.columns c
                WHERE o.[object_id] = c.[object_id]
                    AND TYPE_NAME(c.system_type_id) = 'DATETIME'
                    AND c.name IN ('CreatedBy', 'CreatedDate', 'ModifiedBy', 'ModifiedDate')
            )
        FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, '')

    EXEC sys.sp_executesql @SQL

END
GO

将新表保存在SSMS或任何其他类似产品中。在它重新打开你的桌子之后 -

ttt

于 2013-09-26T06:52:23.087 回答