varname
and @varname
are two DIFFERENT variables!
@varname
- user-defined variable.
Exists always. Even when it was not initialized and/or used, in such case it has NULL value. I.e. it does not need in declaration.
Have no datatype (or it has dynamic datatype). Datatype may be easily changed by assigning the value of another datatype.
This variable has a scope of a connection. I.e. it exists until the connection exists, and its value is not altered until it is altered explicitly. Each connection has its own variavle with the same name, they do not interfere.
For example, you may set it to some value, then use/alter this value in called stored procedure, then use the value altered in the procedure in outer code after the procedure finished.
varname - local (declared) variable
Not exists in anonymous code, exists only within compound (BEGIN-END) code block. Must be declared explicitly at the beginning of the block. Is destroyed at the end of the block. Special type of local variable is function/procedure parameter - it is declared in function/procedure header and exists within the function/procedure code block.
Has definite datatype. Cannot be re-declared.
Has a scope of a block where it is defined.
If a variable and a column with the same name exists in some scope, then the variable has priority and masks the column, so if you need to access the column you must specify table alias.
In most constructions any variable type may be used. But sometimes only one of types may be used - consult User Manual.
1.using @ like set @varname= varcontent
This statement initializes user-defined variable with some value.
2.using declare like declare varname vartype
This statement declares local variable. May posess at the beginning of BEGIN-END block. Does not set a value to the variable (it is NULL).
3.using directly set varname=varcontent
without declare
Causes an error.