辛辛苦苦將數據導入到數據庫中,卻發現忘記創建腳本中忘記PK了。
好在表都有規律,每個表有個 [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