How to declare a variable in SQL Server and use it in the same Stored Procedure

后端 未结 4 1050
再見小時候
再見小時候 2021-02-03 17:57

Im trying to get the value from BrandID in one table and add it to another table. But I can\'t get it to work. Anybody know how to do it right?

CREATE PROCEDURE          


        
4条回答
  •  臣服心动
    2021-02-03 18:34

    What's going wrong with what you have? What error do you get, or what result do or don't you get that doesn't match your expectations?

    I can see the following issues with that SP, which may or may not relate to your problem:

    • You have an extraneous ) after @BrandName in your SELECT (at the end)
    • You're not setting @CategoryID or @BrandName to anything anywhere (they're local variables, but you don't assign values to them)

    Edit Responding to your comment: The error is telling you that you haven't declared any parameters for the SP (and you haven't), but you called it with parameters. Based on your reply about @CategoryID, I'm guessing you wanted it to be a parameter rather than a local variable. Try this:

    CREATE PROCEDURE AddBrand
       @BrandName nvarchar(50),
       @CategoryID int
    AS
    BEGIN
       DECLARE @BrandID int
    
       SELECT @BrandID = BrandID FROM tblBrand WHERE BrandName = @BrandName
    
       INSERT INTO tblBrandinCategory (CategoryID, BrandID) VALUES (@CategoryID, @BrandID)
    END
    

    You would then call this like this:

    EXEC AddBrand 'Gucci', 23
    

    ...assuming the brand name was 'Gucci' and category ID was 23.

提交回复
热议问题