Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use local variables in stored procedures?

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?

like image 397
ram Avatar asked May 27 '10 12:05

ram


People also ask

How do you use a variable in a 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.

Can we use variables in stored procedure?

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.

Can I use global variables in stored procedure or function?

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 ...

How do you DECLARE a local variable in SQL?

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.


1 Answers

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
like image 187
Neil Knight Avatar answered Oct 12 '22 20:10

Neil Knight