我的专栏示例:
(name) as varchar(50)
s01
s02
s16
我想选择第一个缺少0以上的面板名称也使用case和cast(在我的例子中所需的select将是's03')
WITH cte AS(
SELECT name
FROM customers
UNION ALL
SELECT 0
)
SELECT CASE WHEN cast(min(right(name, 2) + 1) as varchar(50)) < 10 THEN 's0' ELSE 's' END +
cast(min(right(name, 2) + 1) as varchar(50))
FROM cte
WHERE NOT EXISTS (
SELECT name
FROM customers
WHERE cast(right(customers.name, 2) as varchar(50)) = cast(right(cte.name, 2) as varchar(50))+1)
此代码有效但仅在我的表为空或表仅包含数字的情况下。
示例我的列名称&gt;结果将是s03
1 or 101
2 102
16 116
但是当它包含字母
时 example my columns in name
s01
s02
s016
它不起作用。我收到一个错误:将varchar值's01'转换为数据类型int时转换失败。我应该把其他地方转换为varchar吗?
答案 0 :(得分:1)
(代表OP发布)。
只需转换联合选择。
WITH cte AS(
SELECT name
FROM customers
UNION ALL
SELECT CAST(0 AS VARCHAR(50))
FROM INVENTORYPANELCAPTIONS
)
SELECT CASE WHEN cast(min(right(name, 2) + 1) as varchar(50)) < 10 THEN 's0' ELSE 's' END
+ cast(min(right(name, 2) + 1) as varchar(50))
FROM cte
WHERE NOT EXISTS (
SELECT name
FROM customers
WHERE right(customers.name, 2)= right(cte.name, 2)+1)
答案 1 :(得分:0)
您正在将字符串(varchar)与int值进行比较,因此在将intchar值与int值进行比较或对它们执行某些操作之前,请尝试将varchar数字转换为int而不是varchar
也许这样的事情(不确定这是否会起作用,但只是将其作为示例写出解决方案的外观):
WITH cte AS(SELECT panelname FROM inventorypanelcaptions UNION ALL SELECT 0)
SELECT CASE WHEN min(cast(right(panelname, 2) as int)) + 1 < 10 THEN 'o0' ELSE 'o' + cast(min(cast(right(panelname, 2) as int)) + 1 as varchar(50)) END
FROM cte
WHERE NOT EXISTS (SELECT panelname FROM inventorypanelcaptions WHERE cast(right(inventorypanelcaptions.panelname, 2) as int) = cast(right(cte.panelname, 2) as int) + 1)