gpt4 book ai didi

sql - 存储过程中表变量的复合主键

转载 作者:行者123 更新时间:2023-12-01 18:06:25 25 4
gpt4 key购买 nike

我是存储过程新手,正在尝试向表变量添加复合主键。

DECLARE @statistictemp TABLE (
MajorName VARCHAR(50) NOT NULL,
SubName VARCHAR(50) NOT NULL,
DetailedName VARCHAR(50) NOT NULL,
UniversityID SMALLINT NOT NULL,
StatisticValue DECIMAL(9,3)
);

ALTER TABLE @statistictemp
ADD CONSTRAINT pk_statistictemp
PRIMARY KEY (MajorName, SubName, DetailedName, UniversityID);

我在 ALTER TABLE @statistictemp 上收到错误消息

Incorrect syntax near '@statistictemp'. Expecting ID, QUOTED_ID, or
'.'.

我在这里做错了什么?如何向表变量添加复合主键?

最佳答案

你可以这样做:

DECLARE @statistictemp TABLE (
MajorName VARCHAR(50) NOT NULL,
SubName VARCHAR(50) NOT NULL,
DetailedName VARCHAR(50) NOT NULL,
UniversityID SMALLINT NOT NULL,
StatisticValue DECIMAL(9,3),
PRIMARY KEY (MajorName, SubName, DetailedName, UniversityID)
);

您可以通过尝试插入重复项来测试主键约束是否有效:例如,

INSERT INTO @statistictemp(MajorName, SubName, DetailedName, UniversityID) SELECT 'a','b','c',1
INSERT INTO @statistictemp(MajorName, SubName, DetailedName, UniversityID) SELECT 'a','b','c',1

第二条语句会抛出错误:

Msg 2627, Level 14, State 1, Line 13
Violation of PRIMARY KEY constraint 'PK_#1EA48E8_B595483D208CD6FA'. Cannot insert duplicate key in object 'dbo.@statistictemp'.
The statement has been terminated.

关于sql - 存储过程中表变量的复合主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9323533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com