Question : How to use variables in a SQL script

I use Ms Sql 2000/2005.

I would like to use variables to run a the following script (I'm not familiar with the syntax, so I just place the variables where I need them, hope its understandable):

   VARIABLE1='/'
   VARIABLE2='33.50'
   VARIABLE3='Center'

   select t.DOCNBR,t.ITEMNMBR,t.TRXQTY, i.IVIVINDX
          g.actnumbr1 + VARIABLE1 + g.actnumbr2+ VARIABLE1 + g.actnumbr3, (g.sales * VARIABLE2)
          from InvtMast t
   join InvtMast i on i.ITEMNMBR=t.ITEMNMBR
   join InvtLINES g on i.IVIVINDX=g.actindx
   where i.ITEMNMBR='BASK'
   and t.DOCNBR=VARIABLE3

Answer : How to use variables in a SQL script

A simplistic answer would be below.  You declare the variables and then use them.  Your declarations should be of the correct type to avoid using CAST/CONVERT in the SQL script to coerce them to the data type you want.



Declare @VARIABLE1 varchar(1), @VARIABLE2 varchar(10), @VARIABLE3 varchar(20)

Set @VARIABLE1='/'
Set @VARIABLE2='33.50'
Set @VARIABLE3='Center'

   select t.DOCNBR,t.ITEMNMBR,t.TRXQTY, i.IVIVINDX
          g.actnumbr1 + @VARIABLE1 + g.actnumbr2+ @VARIABLE1 + g.actnumbr3, (g.sales * @VARIABLE2)
          from InvtMast t
   join InvtMast i on i.ITEMNMBR=t.ITEMNMBR
   join InvtLINES g on i.IVIVINDX=g.actindx
   where i.ITEMNMBR='BASK'
   and t.DOCNBR=@VARIABLE3
Random Solutions  
 
programming4us programming4us