I have a sql table with id (guid) column. how can I force the DB to auto generate a new guid for every new record?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Add DEFAULT(newid())
.
回答2:
Using the DEFAULT(newid()) approach, as @SLaks mentioned, you would allow anyone to alter the Guid value from the Guid column, and that could be bad.
One approach to avoid that would be setting the "Guid" Column as a Persisted Computed Column. That way you couldn't even "force" another value onto the Column. But, since the NEWID() function is Non Deterministic, you couldn't define the Computed Column as Persisted, and the whole approach goes down, since not setting is as Persisted would result as a new Guid everytime you Select that row.
That said, I believe you have 2 choices: Stick with the DEFAULT(newid()) approach or work with Triggers for that.
回答3:
Please try using the following query:
CREATE TABLE TEST
(
ID UNIQUEIDENTIFIER DEFAULT NEWSEQUENTIALID() PRIMARY KEY,
TESTCOLUMN CHAR(2000) DEFAULT REPLICATE('X',2000)
)
GO