我有表dbo.Register具有唯一ID列.我需要在这个表中插入许多行,但是任何具有唯一标识符的行,例如:
INSERT INTO dbo.Register (ID, Name, State, Comment) Select NEWID(), Name, State, Comment From dbo.OtherTable
但是NEWID()返回长字符串:2D0D098E-2FFE-428A-B4EF-950C89FFF83A,但我需要唯一的整数ID.例如,此表中的下一个免费ID.
编辑.我无法修改此表.我只需要在当前结构中插入行.
样本记录:
+--------+------------+--------------+------------+ | ID | Name | State | Comment | +--------+------------+--------------+------------+ | 153299 | Zapytania | Przyjeto | NieDotyczy | | 153300 | Zapytania | Przyjeto | NieDotyczy | | 153301 | Zapytania | Przyjeto | NieDotyczy | | 153302 | Zapytania | Przyjeto | NieDotyczy | | 153303 | Zapytania | Przyjeto | NieDotyczy | | 153304 | Dyspozycje | Zakonczono | NieDotyczy | | 153305 | Zapytania | DoRealizacji | NULL | | 153306 | Zapytania | Przyjeto | NieDotyczy | | 153307 | Zapytania | Przyjeto | NieDotyczy | | 153308 | Dyspozycje | Przyjeto | NieDotyczy | +--------+------------+--------------+------------+
ID列的定义已经是:
[ID] [int] IDENTITY(1,1) NOT NULL,
Shakeer Mirz.. 5
您可以通过以下操作完成此操作
DECLARE @ID INT; SELECT @ID=ISNULL(MAX(ID),0) FROM dbo.Register --Isnull to handle first record for the table INSERT INTO dbo.Register (ID, Name, State, Comment) Select ROW_NUMBER() OVER(ORDER BY(SELECT 1))+ @ID, Name, State, Comment From dbo.OtherTable
根据编辑,无需在"插入"列表中指定列.您可以跳过该列并执行INSERT和SELECT.
INSERT INTO dbo.Register ( Name, State, Comment) Select Name, State, Comment From dbo.OtherTable
你需要更好地了解IDENTITY(属性)(Transact-SQL)
您可以通过以下操作完成此操作
DECLARE @ID INT; SELECT @ID=ISNULL(MAX(ID),0) FROM dbo.Register --Isnull to handle first record for the table INSERT INTO dbo.Register (ID, Name, State, Comment) Select ROW_NUMBER() OVER(ORDER BY(SELECT 1))+ @ID, Name, State, Comment From dbo.OtherTable
根据编辑,无需在"插入"列表中指定列.您可以跳过该列并执行INSERT和SELECT.
INSERT INTO dbo.Register ( Name, State, Comment) Select Name, State, Comment From dbo.OtherTable
你需要更好地了解IDENTITY(属性)(Transact-SQL)