3

我编写了以下 SQL 存储过程,它一直在给我错误 @pid = SELECT MAX(...整个过程是:

Alter PROCEDURE insert_partyco
@pname varchar(200)
AS
BEGIN
    DECLARE @pid varchar(200);

    @pid = SELECT MAX(party_id)+1 FROM PARTY;
    INSERT INTO party(party_id, name) VALUES(@pid, @pname)
    SELECT SCOPE_IDENTITY() as PARTY_ID
END
GO

谁能告诉我我在这里做错了什么?

4

3 回答 3

5
Alter PROCEDURE insert_partyco
@pname varchar(200)
AS
BEGIN
    DECLARE @pid varchar(200);

    SELECT @pid = MAX(party_id)+1 FROM PARTY;
    INSERT INTO party(party_id, name) VALUES(@pid, @pname)
    SELECT SCOPE_IDENTITY() as PARTY_ID
END

SET与 with相比,这有一个优势SELECT,您可以在一个语句中选择多个变量中的表达式:

SELECT @var1 = exp1, @var2 = expr2 ... etc
于 2013-10-05T13:49:03.830 回答
1
declare @total int

select @total = count(*) from news;

select * from news where newsid = @total+2

//**news** table name and **newsid** column name
于 2015-04-21T12:56:26.577 回答
0

您需要使用 SET。

Alter PROCEDURE insert_partyco
@pname varchar(200)
AS
BEGIN
    DECLARE @pid varchar(200);

    SET @pid = (SELECT MAX(party_id)+1 FROM PARTY);
    INSERT INTO party(party_id, name) VALUES(@pid, @pname)
    SELECT SCOPE_IDENTITY() as PARTY_ID
END
GO

或者,在您的情况下,您可以将 party_id 设为自动递增值,因此您无需查询表。

于 2013-10-05T13:49:00.923 回答