我已經創建了一個存儲過程,它爲您提供了哪些工作。 首先我們必須刪除所有外鍵,否則我們不能刪除首要關鍵約束。 阿爾特我們環路鍵刪除並重新創建它們
Create procedure proc_changepk
As
--first drop all references
declare @sql nvarchar(max)
declare cursRef cursor for
SELECT
'ALTER TABLE [' + OBJECT_SCHEMA_NAME(parent_object_id) +
'].[' + OBJECT_NAME(parent_object_id) +
'] DROP CONSTRAINT [' + name + ']' as ref
FROM sys.foreign_keys
open cursRef
fetch next from cursRef into @sql
while @@fetch_status = 0 begin
exec(@sql)
fetch next from cursRef into @sql
end
close cursRef
deallocate cursRef
--drop and recreate primairy keys
declare @pktable table (constraintname nvarchar(255),tablename nvarchar(255),colname nvarchar(255))
insert into @pktable(constraintname,tablename,colname)
SELECT CONSTRAINT_NAME,TABLE_NAME,COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
declare @pkname nvarchar(255),@tablename nvarchar(255),@cols nvarchar(255)
declare Mycurs cursor for
--maybe more than one col for primairy key
SELECT
p.constraintname,p.tablename,
STUFF((SELECT '. ' + colname from @pktable where constraintname=p.constraintname
FOR XML PATH('')), 1, 1, '') [cols]
FROM @pktable p
GROUP BY constraintname,tablename
open mycurs
fetch next from mycurs into @pkname,@tablename,@cols
while @@fetch_status = 0 begin
--drop key
set @sql='alter table ' + @tablename + ' drop CONSTRAINT [' + @pkname + ']'
print @sql
exec(@sql)
--create key
set @sql='alter table ' + @tablename + ' add CONSTRAINT [pk_' + @tablename + '] primary key NONCLUSTERED (' + ltrim(@cols) + ')'
print @sql
exec(@sql)
fetch next from mycurs into @pkname,@tablename,@cols
end
close MyCurs
deallocate MyCurs
GO
這聽起來像你指的是指數,而不是實際領域。 您的實際字段名稱可能類似於'dbo.Batch_Claims.BatchClaimID' – 2010-03-29 17:40:17
Pk_dbo.Batch_Claims是我在KEYS文件夾中看到的,它顯示在SSMS中的Batch_Claims表中,所以我認爲這是表的索引。當爲表確定主鍵時,SQL Server不會自動創建它。你可以刪除一個索引而不影響主鍵或者它們是一樣的嗎? – user234872 2010-03-29 18:23:35
根據我的經驗,ODBC連接需要連接字符串。發佈該信息可能會有所幫助。 – Smandoli 2010-04-01 03:47:09