2

I have written the following SQL Stored Procedure, and it keeps giving me the error at @pid = SELECT MAX(... The whole procedure is:

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

Can anyone please tell me what I'm doing wrong here?

1
  • As @jyparask has said - you can make the id column auto-increment, though I'm not sure why you've declared pid as a varchar when it appears to be an int value... Commented Oct 5, 2013 at 13:52

3 Answers 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

This has an advantage over SET with SELECT in that you can select expressions in multiple variables in one statement:

SELECT @var1 = exp1, @var2 = expr2 ... etc
Sign up to request clarification or add additional context in comments.

Comments

1
declare @total int

select @total = count(*) from news;

select * from news where newsid = @total+2

//**news** table name and **newsid** column name

Comments

0

You need to use 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

Alternatively, in your case you could make party_id an autoincremented value, so you wouldn't need to query the table.

4 Comments

Alternatively you can use SELECT @variable = <expression> as you can then select multiple results into multiple variables in a single statement
Yes, i know, it is just the closer to his try.
@Jyparask! in the alternative case, as you suggested, wouldn't it effect if we want to insert the value by ourserlves somewhere else?
@KamranAhmed Since you are selecting SCOPE_IDENTITY you will get the newly inserted id.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.