ALTER TABLE约束问题
我正在尝试运行以下 SQL 语句:
IF OBJECT_ID('MyTable') IS NOT NULL
DROP TABLE MyTable
SELECT
a.UserId
INTO
MyTable
FROM
UsersTable a
WHERE
a.UserId='12359670-1DC9-4A0A-8AE5-29B664C1A57E'
ALTER TABLE MyTable ALTER COLUMN UserId UNIQUEIDENTIFIER NOT NULL
ALTER TABLE MyTable ADD PRIMARY KEY(UserId)
但是,我收到以下错误: 无法在表“MyTable”中的可空列上定义 PRIMARY KEY 约束。
有什么想法吗?
I'm trying to run the following SQL statement:
IF OBJECT_ID('MyTable') IS NOT NULL
DROP TABLE MyTable
SELECT
a.UserId
INTO
MyTable
FROM
UsersTable a
WHERE
a.UserId='12359670-1DC9-4A0A-8AE5-29B664C1A57E'
ALTER TABLE MyTable ALTER COLUMN UserId UNIQUEIDENTIFIER NOT NULL
ALTER TABLE MyTable ADD PRIMARY KEY(UserId)
However, I get the following error:
Cannot define PRIMARY KEY constraint on nullable column in table 'MyTable'.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这假设 SQL Server 基于 UNIQUEIDENTIFIER
在批处理
编译时,该列可以为空。所以把批次分开。
SQL 不是逐行的过程语言,
您必须在存储过程中执行此操作
This assumes SQL Server based on
UNIQUEIDENTIFIER
Put a GO between (or relevant batch separator if not SQL Server)
At batch compile time, the column is nullable. So break up the batches.
SQL isn't a line by line procedural language
You'll have to do this in a stored procedure
找到了解决方案。
我正在使用以下语句:
Found a solution.
I'm using the following statement:
您不需要动态 SQL。只需先创建表和键即可。
You don't need dynamic SQL. Just create the table and the key first.