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
Author
Message
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: 2 days ago @ 6:06 AM
Points: 28, Visits: 78
Hi,

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

SELECT *
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


SSCrazy

SSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazy

Group: General Forum Members
Last Login: Yesterday @ 4:36 PM
Points: 2,694, Visits: 3,752
One of many methods ....
DECLARE @OrderTypes TABLE
(OrderType CHAR(2))

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

SELECT *
FROM SalesOrders AS SO
INNER JOIN @OrderTypes AS OT
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


SSCoach

SSCoachSSCoachSSCoachSSCoachSSCoachSSCoachSSCoachSSCoachSSCoachSSCoachSSCoach

Group: General Forum Members
Last Login: Yesterday @ 12:12 PM
Points: 15,517, Visits: 27,896
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 2012 Query Performance Tuning
SQL Server 2008 Query Performance Tuning Distilled
and
SQL Server Execution Plans

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

Add to briefcase

Permissions Expand / Collapse