1

I have a table that is structured like this:

|ROWID |COUNTRY|PRICE|
|1     |US     |15|
|1     |UK     |10|
|1     |EU     |12|

I need to select the values from multiple rows into variables for use throughout a stored procedure, doing something like this:

DECLARE @USprice int,@UKprice int
SELECT @USprice = T.Price FROM Table T WHERE T.Country = 'US'
SELECT @UKprice = T.Price FROM Table T WHERE T.Country = 'UK'

The question is what's the fastest way to run this select? In reality I need to get about a dozen rows so am concerned about performance.

Would it be better to do this:

DECLARE @USprice int,@UKprice int
SELECT @USprice = CASE WHEN T.Country = 'US' THEN T.Price ELSE @USprice END
,@UKprice = CASE WHEN T.Country = 'UK' THEN T.Price ELSE @UKprice END
FROM Table T WHERE T.Country IN ('US','UK')
4
  • Which dbms are you using? (That code doesn't look like ANSI SQL.) Commented Oct 11, 2016 at 9:47
  • Looks like T-SQL (MS-SQL-Server) Commented Oct 11, 2016 at 9:52
  • Both of the approaches will work,but you will be getting last values assigned to variables,if price returns more than one value.You can join this tables,instead of assigning variables Commented Oct 11, 2016 at 9:57
  • Also you can use Space and enter as well for formatting,no need of html ..stackoverflow.com/editing-help Commented Oct 11, 2016 at 10:05

1 Answer 1

2

I will not go with the first approach which require individual table hit for each variable which is not efficient

Here is the correct way to achieve the goal using your second approach. You need to add Min/Max aggregate on top of your case statement.

DECLARE @USprice INT,
        @UKprice INT
SELECT @USprice = Max(CASE WHEN T.Country = 'US' THEN T.Price ELSE NULL END),
       @UKprice = Max(CASE WHEN T.Country = 'UK' THEN T.Price ELSE NULL END)
FROM   Table T
WHERE  T.Country IN ( 'US', 'UK' ) 

Considering the T.Country column is not duplicated

Sign up to request clarification or add additional context in comments.

2 Comments

For the OP's benefit ; Not putting ELSE in there creates an implicit ELSE NULL. And then NULL is always treated "last" in MAX().
@MatBailie - added to the solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.