How can I replace a large amount of expressions with a variable or alias?
This may be a rather easy question, however I cannot find an answer on this site (or any other).
I have a rather large CASE expression I need to use multiple times in a script. My script looks something like this:
SELECT
CASE
WHEN ...
WHEN ...
...
END as long_case_expression
FROM table
GROUP BY
CASE
WHEN ...
开发者_开发技巧 WHEN ...
...
END
It would make my life so much easier if I could replace this large amount of WHEN expressions with a variable or alias. That way, my script isn't bloated with a large amount WHEN expressions and I only have to make edits in one place. So, I want it to look like:
SELECT
CASE
@tinyvariable
END
FROM table
GROUP BY
CASE
@tinyvariable
END
I tried just declaring @tinyvariable as a VARCHAR and setting @tinyvariable equal to the huge string of WHEN expressions, but I guess SQL doesn't like that. So, I need the help of someone who knows what they are doing. Please help.
As a note, I'm using SQL Server 2008.
Why dont you wrap the SQL with CASE in another SELECT and then apply the group by using the alias. i.e:
SELECT long_case_expression, COUNT(1)
FROM
(
SELECT
CASE
WHEN ...
WHEN ...
...
END as long_case_expression
FROM table
) a
GROUP BY long_case_expression
You'll lose a bit of efficiency, but creating functions that encapsulates the logic of the CASE statement would definitely make the code easier to read
SELECT function_name( <<parameter list>> )
FROM table
GROUP BY function_name( <<parameter list>> )
An alternative that I wouldn't generally recommend because it can make your query rather brittle would be to use ordinal position notation, i.e.
SELECT
CASE
WHEN ...
WHEN ...
...
END
FROM table
GROUP BY 1
精彩评论