I have a view with many columns and a query builder that will eventually add a MAX
statement on the query. Problem is, when the column type is BIT I cannot use MAX
on it, so I need to check type before. I cannot check the data type of the column during the query builder, so I need a SQL solution that works fine for any data type.
Here is an example (the SELECT
within the CTE
represents a VIEW
which can have any type of data on mycol
, for this first example I'm simulating a BIT
. The MAX
portion is where I need to work on):
ORIGINAL
WITH cte (mycol) AS
(
SELECT CAST(1 as BIT) as mycol
)
SELECT
MAX(mycol) as mycol_max
FROM cte
I got this error:
Operand data type bit is invalid for max operator.
CASTING
If I do the following it will work:
WITH cte (mycol) AS
(
SELECT CAST(1 as BIT) as mycol
)
SELECT
MAX(CAST(mycol as INT)) as mycol_max
FROM cte
However, if mycol
is a string (SELECT 'test' as mycol), I got this error:
Conversion failed when converting the varchar value 'test' to data type int.
So, I tried to check type using some different approaches:
ISNUMERIC()
WITH cte (mycol) AS
(
SELECT 'test' as mycol
)
SELECT
MAX(CASE
WHEN 1 = ISNUMERIC(mycol)
THEN CAST(mycol AS INT)
ELSE mycol
END) AS mycol_max
FROM cte
NOT LIKE %[^0-9]%
WITH cte (mycol) AS
(
SELECT 'test' as mycol
)
SELECT
MAX(CASE
WHEN "mycol" NOT LIKE '%[^0-9]%'
THEN CAST(mycol AS INT)
ELSE mycol
END) AS mycol_max
FROM cte;
TRY_PARSE
WITH cte (mycol) AS
(
SELECT 'test' as mycol
)
SELECT
MAX(CASE
WHEN TRY_PARSE(mycol AS INT) IS NOT NULL
THEN CAST(mycol AS INT)
ELSE mycol
END) AS mycol_max
FROM cte
All of these returned the error
Conversion failed when converting the varchar value 'test' to data type int.
Also, if mycol
is an integer:
WITH cte (mycol) AS
(
SELECT 1 as mycol
)
...
I got
Argument data type int is invalid for argument 1 of parse function.
So, all I need is to allow anything into the MAX()
statement. I tried checking and converting, but didn't get any satisfactory solution. How can I do it?
Thanks
Using SQL Server 2017.
BIT Won't behave as int so MAX won't really work unless you just choose max LEN which is still not optimal. You might try ORDER BY DESC but I doubt it will help. You might as well add another column that will specify what exactly MAX you're looking for.
SELECT TOP 1 CAST(1 as BIT) as mycol
FROM TB1
ORDER BY mycol DESC
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.