cancel
Showing results for 
Search instead for 
Did you mean: 

CREATE VARIABLE vs DECLARE statement

Former Member
5,034

Hi,

What is the difference between the DECLARE statement and the CREATE VARIABLE Statement? And is it general practice to run a DROP VARIABLE at the end of the script when using these statements?

I read the online SQL manual for these but I still can't distinguish the difference in functionality apart from the DECLARE being used between a BEGIN and END.

Thanks,

Warren.

Accepted Solutions (1)

Accepted Solutions (1)

VolkerBarth
Contributor

I would say a variable created with CREATE VARIABLE is a connection-specific global variable, i.e. it is accessible by all SQL statements of the current connection and can be changed by all these statements. There can only be one variable of that particular name at any time on one connection.

One would usually drop that variable when it is no more used. When the connection is closed, the variable is dropped automatically.

In contrast, DECLARE creates a local variable with block scope, i.e. it is visible and accessible within its block. AFAIK no variable of that particular name can be used in inner blocks (in constrast to typical programming languages where a variable v in an inner block "hides" a variable v in an outer block). (Note: I haven't tested that behaviour myself). Otherwise, this is the common kind of variable to use in stored procedures and the like.

As to the usage:

I would recommend to use local variables whenever possible.

CREATE VARIABLE is useful (and sometimes the most fitting approach) when you have to change behaviour on a "global scope", usually in more advanced situations. It often works like some kind of option. Some examples:

  • One can use such a variable to change the behaviour of many/all triggers - cf. this question.
  • One could filter results based on a connection-specific values (say, to list only the customers of a particular sales person) by including a filter value in the variable and use that in the WHERE clause of all according queries.

Besides that, in my opinion a global varible in SQL is possibly as "dangerous" as in other programming languages and should be handled with according care.

Former Member

Volker: I just want to say Thanks for all the material you have posted in this site. I have learned a lot from your answers as well as your questions. You have added a lot to my knowledge of SQLA.

VolkerBarth
Contributor
0 Kudos

@Bill: That's really nice to hear - thank you! I feel that sharing what one is about to learn or has just learnt is usually as valueable as sharing one's sound knowledge. I'm glad that this site is about both sides of the story... And frankly, I have learnt much more about SQL Anywhere since this site has been created than I'v learnt in the time before, too.

Former Member
0 Kudos

Ahh, thanks for the detailed explanation. It makes sense now!

Answers (0)