SQL Server, select CASE with different cast
This works for me. Check if @id is int and if all values in Code column can be cast to int .
UPDATE If you have a value that cannot be executed for an int, your query will not work.
So, you can write 2 different queries.
Smth like
IF @id = 1 THEN
SELECT code ...
ELSE
SELECT Cast(Code AS int) as Code
a source to share
Why do this? A SQL Server expression has one fixed type. In other words, one expression cannot be varchar(50)
or int
depending on how the expression is evaluated. You can apply each case to sql_variant
, but it may or may not make sense depending on what you are trying to do.
EDIT
If you are executing this query from a stored procedure, you can create an IF..ELSE block to execute a different version of the query based on the @ID value. For instance:
IF (@ID = 1) BEGIN
SELECT Cast(Code AS int) AS Code FROM ...
END
ELSE BEGIN
SELECT Code FROM ...
END
a source to share