question

spatel avatar image
spatel asked

declare variable

How can we know where and when we have to declare a variable.
variable
10 |1200 characters needed characters left characters exceeded

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

ThomasRushton avatar image
ThomasRushton answered
Variables in T-SQL need to be declared. How do you know where & when you need to do this? Well, in SSMS with IntelliSense enabled, you'll see red wibbly underlining when you reference a variable that hasn't been declared. You also won't see an undeclared variable in any of the intellisense dropdowns. Red-Gate's SQL Prompt has similar functionality - check the screenshots at http://www.red-gate.com/products/sql-development/sql-prompt/screenshots
10 |1200 characters needed characters left characters exceeded

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Grant Fritchey avatar image
Grant Fritchey answered
If you need to use a variable in statement, you have to declare. If you've declared a parameter as part of a stored procedure, you don't need to also declare it as a variable. They're two different things: CREATE PROCEDURE dbo.MyNewProc (@MyParameter BIGINT) AS BEGIN DECLARE @MyVariable VARCHAR(50) = 'Hello World'; SELECT a.* FROM dbo.Agent AS a WHERE a.AgentName = @MyVariable AND a.AgentId = @MyParameter; END You can see that the parameter is part of the declare of the procedure and the variable is part of the code of the procedure.
10 |1200 characters needed characters left characters exceeded

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.