辛辛苦苦将数据导入到DB中,却发现忘记创建脚本中忘记PK了。
好在Table都有规律,每个表有个[ID] int字段,PK是建立在其上的。
注:
1)为了代码的可读性,没有采用‘SQL拼接’方法,而是采用了‘先占位,后替换’的方法--看里面的Replace语句。推荐给大家
2)由于是执行DDL,出于谨慎考虑,‘生成’而非‘直接执行’SQL。若不然,读者可以将里面的EXEC语句去掉注释。
----这是代码---------------------------------------
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- -- =============================================
- -- Author: Yew
- -- Create date: 2011-06-12
- -- Description: 为所有表增加PK (on ID)
- /* ---------History----------------------------
- ---------------------------------------------*/
- -- =============================================
- CREATE PROCEDURE [TOOL].[sp_DB_AddPK]
- AS
- BEGIN
- SET NOCOUNT ON;
- DECLARE @vTable varchar(100)
- ,@vSchema varchar(100)
- ,@vSql varchar(max)
- DECLARE cur_ CURSOR FOR
- SELECT [name], schema_name(schema_id)
- FROM sys.objects
- WHERE type in (N'U')
- ORDER BY schema_id, name
- OPEN cur_
- FETCH NEXT FROM cur_ INTO @vTable, @vSchema
- WHILE @@FETCH_STATUS = 0
- BEGIN
- SET @vSQL = N'
- ALTER TABLE [#Schema#].[#Table#] ADD CONSTRAINT [PK_#Table#] PRIMARY KEY CLUSTERED
- (
- [ID] ASC
- )WITH (SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = ON, ONLINE = OFF) ON [PRIMARY]
- GO
- '
- SET @vSQL = Replace(@vSQL, '#Table#', @vTable)
- SET @vSQL = Replace(@vSQL, '#Schema#', @vSchema)
- print @vSql
- -- EXEC (@vSql)
- FETCH NEXT FROM cur_ INTO @vTable, @vSchema
- END
- CLOSE cur_
- DEALLOCATE cur_
- END
----这是代码--------------------------------------------
本文转自DavyYew 51CTO博客,原文链接:http://blog.51cto.com/davyyew/586877,如需转载请自行联系原作者