我有以下SQL语句(适用于SQL Server):
INSERT INTO t1 (c1, c2)
VALUES (1, CASE WHEN (SELECT MAX(c2) FROM t1 AS maxV) IS NOT NULL THEN maxV+1 ELSE 1 END);
我收到错误:“无效的列名'maxV'”
为什么?
答案 0 :(得分:4)
尝试使用COALESCE
:
INSERT INTO t1 (c1, c2)
SELECT 1, COALESCE(MAX(c2), 0) + 1
FROM t1
答案 1 :(得分:1)
试试这个......
INSERT INTO t1 (c1, c2)
VALUES (
1,
CASE
WHEN (SELECT MAX(c2) FROM t1) IS NOT NULL
THEN (SELECT MAX(c2)+1 FROM t1)
ELSE 1
END);
答案 2 :(得分:1)
另一种方式......
INSERT INTO t1 (c1, c2)
VALUES (1, ISNULL(SELECT MAX(c2) FROM t1, 0)+1);