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

后端 未结 4 1052
再見小時候
再見小時候 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:31

    In sql 2012 (and maybe as far back as 2005), you should do this:

    EXEC AddBrand @BrandName = 'Gucci', @CategoryId = 23
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-03 18:36
    CREATE PROCEDURE AddBrand
    @BrandName nvarchar(50) = null,
    @CategoryID int = null
    AS    
    BEGIN
    
    DECLARE @BrandID int = null
    SELECT @BrandID = BrandID FROM tblBrand 
    WHERE BrandName = @BrandName
    
    INSERT INTO tblBrandinCategory (CategoryID, BrandID) 
           VALUES (@CategoryID, @BrandID)
    
    END
    
    EXEC AddBrand @BrandName = 'BMW', @CategoryId = 1
    
    0 讨论(0)
  • 2021-02-03 18:38

    None of the above methods worked for me so i'm posting the way i did

    DELIMITER $$
    CREATE PROCEDURE AddBrand()
    BEGIN 
    
    DECLARE BrandName varchar(50);
    DECLARE CategoryID,BrandID  int;
    SELECT BrandID = BrandID FROM tblBrand 
    WHERE BrandName = BrandName;
    
    INSERT INTO tblBrandinCategory (CategoryID, BrandID) 
           VALUES (CategoryID, BrandID);
    END$$
    
    0 讨论(0)
提交回复
热议问题