无法在SQL中创建表

时间:2017-06-28 18:51:43

标签: sql sql-server tsql

gsub("\\s+", ",", trimws(g1))

这是我正在使用的脚本。它后面跟着错误

create role AppUsers
create user AppUser without login
alter role AppUsers add member AppUser 

alter role AppUsers add member [BUILTIN\Administrators]

我的X表有5个字段,但其中一个是xcode作为主键。

1 个答案:

答案 0 :(得分:0)

您尝试加入的辅助表中没有主键。在您尝试加入的表中添加主键,并确保辅助表类型和主数据库的数据类型相同。

示例:

--Works
IF OBJECT_ID('.X') IS NOT NULL 
    DROP TABLE .X;
CREATE TABLE X (Id INT IDENTITY, YId INT, Val VARCHAR(8), CONSTRAINT PK_X_Id PRIMARY KEY (Id))

IF OBJECT_ID('.Y') IS NOT NULL 
    DROP TABLE .Y;
CREATE TABLE Y (Id INT IDENTITY, Val VARCHAR(8), CONSTRAINT PK_Y_Id PRIMARY KEY (Id))

ALTER TABLE dbo.X
ADD CONSTRAINT FK_X_Y_Id FOREIGN KEY(YId) REFERENCES Y(Id)

--Fails, due to Table Y not having appropriate Primary Key
IF OBJECT_ID('.X') IS NOT NULL 
    DROP TABLE .X;
CREATE TABLE X (Id INT IDENTITY, YId INT, Val VARCHAR(8), CONSTRAINT PK_X_Id PRIMARY KEY (Id))

IF OBJECT_ID('.Y') IS NOT NULL 
    DROP TABLE .Y;
CREATE TABLE Y (Id INT IDENTITY, Val VARCHAR(8))

ALTER TABLE dbo.X
ADD CONSTRAINT FK_X_Y_Id FOREIGN KEY(YId) REFERENCES Y(Id)