TrevorGoodchild
TrevorGoodchild

Reputation: 1060

T-SQL Querying a table using a variable

I have been tasked with updating a stored procedure and I'm trying to figure out the most efficient way of performing the select. Here is the current code, vaultID and clientID are input parameters:

SELECT 
   @siteID = Site.siteID, 
   @siteGroupID = Site.siteGroupID,
   @customerID = Customer.customerID
FROM 
   Customer
INNER JOIN 
   Site ON Customer.siteID = Site.siteID
WHERE 
   Site.phoneNumberIVR = @vaultID 
   AND Site.production = 1
   AND Customer.clientID = @clientID

The update I'm working on has to do with the @clientID variable. If a record has a specific @siteGroupID, the clientID needs to be passed in as it was received. If the record has a different type of @siteGroupID, the @clientID variable needs to be appended with a specific prefix. That prefix is also going to be stored on the site table.

I realize I can make a call to the site table initially to get the prefix, and then modify the @clientID variable, but I'm trying to figure out if there is a way to do this with just one call. I've been trying different case statements but I'm not sure this is even feasible.

Upvotes: 0

Views: 78

Answers (1)

valverij
valverij

Reputation: 4951

If I understand your issue correctly, then you should be able to throw a CASE in your SELECT with your condition to do the appending:

SELECT 
    @siteID = Site.siteID, 
    @siteGroupID = Site.siteGroupID,
    @customerID = Customer.customerID,
    @clientID = 
        CASE
            WHEN Site.siteGroupID = 1234 THEN Site.Prefix + @clientID
            ELSE @clientID
        END
FROM 
    Customer
    inner join Site on Customer.siteID = Site.siteID
WHERE 
    Site.phoneNumberIVR = @vaultID 
    and Site.production = 1
    and Customer.clientID = @clientID

Of course, depending on the datatypes of @clientID and Site.Prefix, you might have to do something other than a simple + to do the appending. For example if both were integer datatypes, you can append then with some CONVERT calls:

@clientID = CONVERT(integer, CONVERT(varchar, Site.Prefix) + CONVERT(varchar, @clientID))

Upvotes: 1

Related Questions