Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the syntax for variables in an MSSQL stored procedure?

I have a simple query like this:

select * from mytable where id > 8

I want to make the 8 a variable. There's some syntax like

declare @myvar int
myvar = 8

but I don't know the exact syntax.

What is it?

Thanks!

like image 461
MrDatabase Avatar asked Oct 21 '08 19:10

MrDatabase


3 Answers

It's:

DECLARE @MyVariable INT
SET @MyVariable = 8
like image 98
Ed Altorfer Avatar answered Nov 17 '22 09:11

Ed Altorfer


declare @myvar int

Set @myvar = 8

select * from mytable where id > @myvar
like image 35
JasonS Avatar answered Nov 17 '22 08:11

JasonS


To clarify: both SET and SELECT work, but SET is the ANSI standard. However, if you're setting multiple values at once, then

SET @one = 1
SET @two = 2

will be very slightly slower than

SELECT @one = 1, @two = 2

What you gain in speed may well be offset by readability and clarity, however.

like image 3
JasonFruit Avatar answered Nov 17 '22 07:11

JasonFruit