if I want to select any id from a table and want to insert it's value in another table as foreign key then how i will do it through stored procedure?
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.
Global variable is bad practice in any programming language. Why not just pass the variable as a parameter in the stored procedure. CREATE PROCEDURE myProcedure ( @MyParameter, @SomeVariable -- the global variable ) AS ...
SQL Variable declarationThe DECLARE statement is used to declare a variable in SQL Server. In the second step, we have to specify the name of the variable. Local variable names have to start with an at (@) sign because this rule is a syntax necessity. Finally, we defined the data type of the variable.
An example of how I would approach this.
DECLARE @MyID INT;
SET @MyID = 0;
SELECT @MyID = [TableID]
FROM [MyTable]
WHERE [TableID] = 99;
IF @MyID > 0
BEGIN
INSERT INTO [MySecondTable]
VALUES (@MyID, othervalues);
END
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