How do I make the following T-SQL statement legal? I can copy the subquery that sets @Type variable for every CASE option, but I’d rather execute the subquery only once. Is it possible?
SELECT
@Type = (SELECT CustomerType FROM dbo.Customers WHERE CustomerId = (SELECT CustomerId FROM dbo.CustomerCategories WHERE CatId= @CatId)),
CASE
WHEN @Type = 'Consumer'THEN dbo.Products.FriendlyName
WHEN @Type = 'Company' THEN dbo.Products.BusinessName
WHEN @Type IS NULL THEN dbo.Products.FriendlyName
WHEN @Type = '' THEN dbo.Products.FriendlyName
END Product,
...
FROM
Products
INNER JOIN
Category
...
Edit: modified my example to be more concrete…have to run now…will be back tomorrow…sorry for signing off short but have to pick up kids 😀 will check back tomorrow. THX!!
Clarification: I can’t separate the two: in the subquery’s where-clasue, I need to refer to columns from tables that’re used in the main query’s join stmt. If I separate them, then @Type will lose relevance.
Why not just separate it into two operations? What do you think you gain by trying to glom them into a single statement?
At the risk of sounding obtuse, do you really need the variable at all? Why not:
With that form you’ll need to decide whether you want to assign values to variables or retrieve results.
You can also pull multiple variables, e.g.
But this is all conjecture, because you haven’t shared enough specifics.
EDIT okay, now that we have a real query and can understand a bit better what you’re after, let’s see if we can write you a new version. I’ll assume that you were only trying to store the @Type variable so you can re-use it within the query, and that you weren’t trying to store a value there to use later (after this query).
Some notes: