我们正在将数据库迁移到AWS,但他们要求我们在数据库中的所有表中都有一个主键。
我们的数据库中有大约50个表,由我们的安装程序添加,但我们没有任何主键。因此,我们需要在每个表中添加一个列作为表主键,并使用唯一值填充它。
编写此脚本的任何帮助都将循环遍历数据库中的所有表,添加一列并使用主键填充该列。
提前致谢。 我得到SQL来更新单个表只需要一种方法来遍历数据库中的所有表:
ALTER TABLE TextEntity ADD TextEntity_id BIGINT IDENTITY;
GO
ALTER TABLE TextEntity
ADD CONSTRAINT PK_TextEntity_id PRIMARY KEY (TextEntity_id);
GO
答案 0 :(得分:3)
类似下面的内容?
select CONCAT('ALTER TABLE ', QUOTENAME(name, '[]'), ' ADD PK_', name, ' int identity(1, 1) Primary Key')
from sys.tables
或者您可以尝试sp_msforeachtable来填充主键
答案 1 :(得分:1)
使用SQL Server元数据表获取要编辑的表的列表,然后创建动态SQL,将新列添加为标识和主键:
DECLARE @script nvarchar(max)='' --contains the dynamic TSQL code
DECLARE @table_schema varchar(max); --contains the name of your schema
DECLARE @table_name varchar(max); --contains the name of your table
DECLARE @key_Cursor as CURSOR; --cursor that will loop on your tables
--Here you must add a condition in the where clause that filters only
--the 50 tables you want to edit
SET @key_Cursor = CURSOR FOR SELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES where TABLE_CATALOG='primary_keys' and TABLE_TYPE='BASE TABLE';
OPEN @key_Cursor;
FETCH NEXT FROM @key_Cursor INTO @table_schema, @table_name;
WHILE @@FETCH_STATUS = 0
BEGIN
--create the script that adds a new identity column called ID
set @script=' alter table ' + @table_schema + '.' + @table_name + ' add id int identity(1,1); '
--add the code that create the primary key using the new ID column
set @script = @script + ' ALTER TABLE ' + @table_schema + '.' + @table_name + ' ADD CONSTRAINT [PK_' + @table_name + '_ID] PRIMARY KEY CLUSTERED ([ID] ASC); '
--execute the script for the current table
exec sp_executesql @script
--print (@script)
--fetch data for the next table
FETCH NEXT FROM @key_Cursor INTO @table_schema, @table_name;
END
CLOSE @key_Cursor;
DEALLOCATE @key_Cursor;
这只是一个草稿脚本,只是为了向您展示如何循环表:它可以工作,但它很容易受到SQL注入。考虑使用参数化查询。