能帮我吗?我写了这段代码,但出现错误
关键字SELECT附近的语法不正确
这是我的代码
CREATE PROCEDURE dbo.spSetCommand
@Client_id INT,
@BcNumber INT,
@ArticleId INT,
@EntryNumber DECIMAL
AS
DECLARE @CommandId INT
BEGIN
INSERT INTO commands(client_id, bc_number, date_command)
VALUES (@Client_id, @BcNumber, GETDATE());
SET @CommandId = SELECT command_id
FROM commands
WHERE bc_number = @BcNumber;
INSERT INTO entries(command_id, article_id, entry_number)
VALUES (@CommandId, @ArticleId, @EntryNumber);
END
有人可以帮助找到问题吗?
答案 0 :(得分:4)
-- need to have brackets
set @CommandId = (SELECT command_id FROM commands WHERE bc_number = @BcNumber);
如果查询有多个结果,将失败,将出现错误。
您也可以使用此:
SELECT @CommandID = command_id
FROM commands
WHERE bc_number = @BcNumber
如果有多个结果,这将为您提供最后一个值(这可能/可能不是您的逻辑选择)
答案 1 :(得分:0)
在SQL SELECT SCOPE_IDENTITY()
中,根据您的情况command_id
返回最近添加的记录身份密钥
CREATE PROCEDURE dbo.spSetCommand
@Client_id INT,
@BcNumber INT,
@ArticleId INT,
@EntryNumber DECIMAL
AS
DECLARE @CommandId INT
BEGIN
INSERT INTO commands(client_id, bc_number, date_command)
VALUES (@Client_id, @BcNumber, GETDATE());
SET @CommandId = SELECT SCOPE_IDENTITY()
INSERT INTO entries(command_id, article_id, entry_number)
VALUES (@CommandId, @ArticleId, @EntryNumber);
END
以下行代码中有错误:
SET @CommandId = SELECT command_id
FROM commands
WHERE bc_number = @BcNumber;
如果存在多个记录WHERE bc_number = @BcNumber
,则将产生错误,否则可以正常工作。
有礼方式如下:
SELECT @CommandId =command_id commands WHERE bc_number = @BcNumber;
但最合适的方法是在当前时刻获取当前表中最近添加的记录,您可以使用SCOPE_IDENTITY()
SQL函数
答案 2 :(得分:0)
SET @CommandId = SELECT command_id
FROM commands
WHERE bc_number = @BcNumber;
代替尝试
SELECT @CommandId = top 1 command_id
FROM commands
WHERE bc_number = @BcNumber order by command_id desc;
我使用set @foo =一些像4这样的整数;然后选择@foo =一些查询;