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.
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.
The SET command is used with UPDATE to specify which columns and values that should be updated in a table.
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.
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.
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.
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