SQL Server - 向所有表添加默认约束

时间:2010-12-19 03:04:12

标签: sql-server tsql sql-server-2008-r2

有没有办法编写一个脚本来检查数据库中的每个表,查找名为uniqueidentifier的{​​{1}}列,然后添加ID约束DEFAULT如果NEWID()约束不存在,则列到列?

1 个答案:

答案 0 :(得分:3)

根据OP的评论说明进行了编辑

此脚本会在名为DEFAULT且尚未NEWID()约束的uniqueidentifier列上创建ID DEFAULT约束。

SET NOCOUNT ON

DECLARE @tableVarId int
DECLARE @alterSql   nvarchar(MAX)

DECLARE @columnsNeedingDefault TABLE
(
  TableVarId    int IDENTITY (1,1) PRIMARY KEY,
  AlterSql      nvarchar(MAX)
)

INSERT INTO @columnsNeedingDefault (AlterSql)
SELECT
  'ALTER TABLE ' + QUOTENAME(a_Table.[name]) +
  ' ADD CONSTRAINT [DF_' + a_Table.[name] + '_' + a_Column.name +
  '] DEFAULT NEWID() FOR ' + QUOTENAME(a_Column.name)
FROM
  sys.columns AS a_Column
INNER JOIN
  sys.tables AS a_Table ON a_Column.[object_id] = a_Table.[object_id]
WHERE
  a_Column.[name] = 'ID'
  AND
  a_Column.user_type_id = 36 -- uniqueidentifier
  AND
  NOT EXISTS
  (
    SELECT
      *
    FROM
      sys.default_constraints AS a_DefaultConstraint
    WHERE   a_DefaultConstraint.parent_object_id = a_Table.[object_id]
      AND   a_DefaultConstraint.parent_column_id = a_Column.column_id
      AND   a_DefaultConstraint.type_desc = 'DEFAULT_CONSTRAINT'
  )

SET @tableVarId = (SELECT MIN(TableVarId) FROM @columnsNeedingDefault)
WHILE @tableVarId IS NOT NULL
  BEGIN
    SELECT @alterSql = AlterSql FROM @columnsNeedingDefault

    PRINT @alterSql
    EXEC sp_executesql @alterSql

    SET @tableVarId = (SELECT MIN(TableVarId) FROM @columnsNeedingDefault
                       WHERE TableVarId > @tableVarId)
  END