我已在SQL中使用此功能将IDENTITY设置为特定值:-
DECLARE @ID int = 42;
DECLARE @TABLENAME varchar(50) = 'tablename'
DECLARE @SQL nvarchar(1000) = 'IF EXISTS (SELECT * FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = '''+@TABLENAME+''' AND last_value IS NOT NULL)
BEGIN
DBCC CHECKIDENT('+@TABLENAME+', RESEED,' + CONVERT(VARCHAR(10),@ID-1)+');
END
ELSE
BEGIN
DBCC CHECKIDENT('+@TABLENAME+', RESEED,' + CONVERT(VARCHAR(10),@ID)+');
END';
EXEC (@SQL);
并在C#中设置特定值:-
SetIdentity(context, "tablename", 42);
.
.
private static void SetIdentity(DbContext context, string table,int id)
{
string str = "IF EXISTS (SELECT * FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = '" + table
+ "' AND last_value IS NOT NULL)\nBEGIN\n";
str += "DBCC CHECKIDENT('" + table + "', RESEED," + (id - 1).ToString() + ");\n";
str += "END\nELSE\nBEGIN\n";
str += "DBCC CHECKIDENT('" + table + "', RESEED," + (id).ToString() + ");\n";
str += "END\n";
context.Database.ExecuteSqlCommand(str);
}
这建立在以上答案的基础上,并始终确保下一个值为42(在这种情况下)。