Domanda

I have the following SQL statement (that is intended for 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);

I get an error: "Invalid column name 'maxV'"

Why?

È stato utile?

Soluzione

Try using COALESCE:

INSERT INTO t1 (c1, c2) 
SELECT 1, COALESCE(MAX(c2), 0) + 1
FROM t1

Altri suggerimenti

Try this...

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);

Another way of doing it...

INSERT INTO t1 (c1, c2) 
VALUES (1, ISNULL(SELECT MAX(c2) FROM t1, 0)+1);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top