Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
Log in  ::  Register  ::  Not logged in
Home       Members    Calendar    Who's On

Add to briefcase

Storing range of varchar values into variable for future filtering in query Expand / Collapse
Posted Tuesday, June 17, 2014 1:20 PM
SSC Rookie

SSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC Rookie

Group: General Forum Members
Last Login: Thursday, August 20, 2015 1:46 PM
Points: 45, Visits: 132

I have a simple query in which I'm retrieving all sales orders of a certain type.

FROM SalesOrders
WHERE SalesOrders.OrderType IN ('10','15','18')

Suppose instead of specifying the OrderType values in the WHERE clause, I want to store them in a variable prior to the SELECT statement and reference the variable in the WHERE (or in a JOIN) instead. What is the best way to handle this?

I greatly appreciate any assistance.
Post #1582560
Posted Tuesday, June 17, 2014 1:23 PM



Group: General Forum Members
Last Login: Thursday, October 1, 2015 8:56 AM
Points: 2,747, Visits: 3,999
One of many methods ....
(OrderType CHAR(2))

INSERT @OrderTypes
VALUES ('10'),('15'),('18')

FROM SalesOrders AS SO
ON SO.OrderType = SO.OrderType


Personal Motto: Why push the envelope when you can just open it?

If you follow the direction given HERE you'll likely increase the number and quality of responses you get to your question.

Jason L. Selburg
Post #1582562
Posted Wednesday, June 18, 2014 4:30 AM



Group: General Forum Members
Last Login: Yesterday @ 8:13 PM
Points: 15,879, Visits: 30,168
Table variables can work, but understand that they don't have statistics which could affect their use in something like a JOIN. You might be better off using a temporary table. That does have statistics created on it.

"The credit belongs to the man who is actually in the arena, whose face is marred by dust and sweat and blood..." Theodore Roosevelt
The Scary DBA
Author of:
SQL Server Query Performance Tuning
SQL Server Execution Plans

Product Evangelist for Red Gate Software
Post #1582794
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse