Click here to monitor SSC
SQLServerCentral is supported by Redgate
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
Valued Member

Valued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued Member

Group: General Forum Members
Last Login: Yesterday @ 9:14 AM
Points: 73, Visits: 213

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: Yesterday @ 8:39 AM
Points: 2,777, Visits: 4,100
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: Today @ 12:17 PM
Points: 17,173, Visits: 32,139
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