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 AddBrand AS DECLARE @BrandName nvarchar(50), @CategoryID int, @BrandID int SELECT @BrandID = BrandID FROM tblBrand WHERE BrandName = @BrandName INSERT INTO tblBrandinCategory (CategoryID, BrandID) VALUES (@CategoryID, @BrandID) RETURN
Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.
A variable is a named data object whose value can change during the stored procedure execution. You typically use variables in stored procedures to hold immediate results. These variables are local to the stored procedure. Before using a variable, you must declare it.
You cannot pass table-valued parameters to CLR user-defined functions. Table-valued parameters can only be indexed to support UNIQUE or PRIMARY KEY constraints. SQL Server does not maintain statistics on table-valued parameters.
Declaring a variable The variable name must start with the @ sign. In this example, the data type of the @model_year variable is SMALLINT . By default, when a variable is declared, its value is set to NULL .
I can see the following issues with that SP, which may or may not relate to your problem:
)
after @BrandName
in your SELECT
(at the end)@CategoryID
or @BrandName
to anything anywhere (they're local variables, but you don't assign values to them)In a comment you've said that after fixing the )
you get the error:
Procedure AddBrand has no parameters and arguments were supplied.
That's telling you that you haven't declared any parameters for the SP, 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), -- These are the @CategoryID int -- parameter declarations 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
or this:
EXEC AddBrand @BrandName = 'Gucci', @CategoryID = 23
...assuming the brand name was 'Gucci' and category ID was 23.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With