将参数放入 SQL 表创建脚本中的 IDENTITY(1,1) 属性中
我想使用参数设置自定义身份。例如:
CREATE TABLE Pets (
PetId int IDENTITY(@Parameter,1) PRIMARY KEY,
PetName varchar(255)
);
My SQL 解析器不接受这样的语法。
I would like to set custom Identity with parameters. For example:
CREATE TABLE Pets (
PetId int IDENTITY(@Parameter,1) PRIMARY KEY,
PetName varchar(255)
);
My SQL parser does not accept such syntax.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用动态 SQL,但这似乎不对。
You can use dynamic SQL but this doesn't seem right.
虽然您确实需要在
CREATE TABLE
语句中使用带有IDENTITY
的文字整数(或根本不需要),但您可以重置IDENTITY
种子值使用支持参数的DBCC CHECKIDENT
创建表后。另外:
NOT NULL
,除非您绝对确定不是这样。NULL
和空白''
值的文本列更烦人的了并且不知道两者之间是否存在任何语义差异。CHECK
约束的用途!CREATE TABLE
中未指定NOT NULL
或NULL
列规范,则 SQL Server 默认假设NULL
。varchar
类型本身支持 Unicode 的其他 RDBMS。无论如何,像这样:
GO
语句是为了 SSMS 的利益;如果您从程序代码中使用此命令,则可能需要将 DBCC CHECKIDENT 命令移动到单独的命令批处理中。关于权限的重要警告:
DBCC CHECKIDENT
来重置表的状态,以运行自动集成测试或其他一些他们有的开发/测试场景>sysadmin
或db_owner
级权限,在这种情况下没有问题。sysadmin
(服务器级)、db_owner
(数据库级)或db_ddladmin
(数据库级)权限那么您将无法使用DBCC CHECKIDENT
,即使您可以创建表的副本、DROP TABLE
原始表并重新创建它作为新的来自文字的IDENTITY
- 这很愚蠢。While you do need to use a literal integer (or none at all) with
IDENTITY
inCREATE TABLE
statements, you can reset theIDENTITY
seed value after you've created the table usingDBCC CHECKIDENT
which does support parameters.Also:
dbo
), otherwise objects might be created in a different schema and names won't be resolved when addressed from objects in other schemas (it helps performance too).NOT NULL
unless you're absolutely certain otherwise.NULL
and blank''
values and no clue about if there's any semantic difference between the two.CHECK
constraints are for, folks!NOT NULL
orNULL
in aCREATE TABLE
column specification then SQL Server defaults to assumingNULL
.nvarchar
and notvarchar
.varchar
types natively support Unicode.Anyway, like this:
GO
statement is for the benefit of SSMS; if you're using this from program code you might need to move theDBCC CHECKIDENT
command to a separate command-batch.Important caveat about permissions:
DBCC CHECKIDENT
to reset a table's state for running automated integration tests or some other dev/test scenario where they havesysadmin
ordb_owner
-level permissions, in which case there's no problem.sysadmin
(Server-level),db_owner
(DB-level), ordb_ddladmin
(DB-level) permissions then you won't be able to useDBCC CHECKIDENT
, even though you can create a copy of the table,DROP TABLE
the original table and recreate it with as newIDENTITY
from a literal - which is just silly.