Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between DECLARE and SET in SQL [closed]

What's the difference between DECLARE and SET using SQL (or more specifically MySQL)?

Both can set variables it seems. I have read the MySQL docs and I did not understand the difference between the two.

like image 705
C H Avatar asked Nov 19 '13 14:11

C H


People also ask

What is DECLARE in SQL?

The DECLARE statement initializes a Transact-SQL variable by: Assigning a name. The name must have a single @ as the first character. Assigning a system-supplied or user-defined data type and a length.

WHAT IS SET command in SQL?

The SET command is used with UPDATE to specify which columns and values that should be updated in a table.

What happens to a declared variable after the Go statement?

Variables declared before the GO statement are not accessible after the GO statement. Basically SSMS sends the first batch (i.e. Batch 1) of statements to the SQL Engine first, once its execution is over it sends the second batch of statements (i.e. Batch 2) after the GO statement to the SQL Engine for execution.

How do you SET a variable in SQL?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.


1 Answers

DECLARE does not initialize the variable. When you declare it you declare the variable name, the type, and a default value, which could be an expression.

SET is for initializing the variable you declared previously, and you cannot SET the variable until you DECLARE it.

like image 105
Hituptony Avatar answered Sep 18 '22 13:09

Hituptony