I have table source SRC
such as:
*Column1*
First
Second
45
Fouth
Now I want to insert these data into table DEST (ID, NAME)
with this logic:
If row is numeric, insert into (ID, NAME) VAUES (45, 'TBD')
.
If the row is not numeric, generate ID and insert into (ID, NAME) VALUES (*GENERATED ID*, NAME).
I tried something like:
DECLARE @i INT;
SELECT @i = MAX ( ID ) + 1
FROM DEST;
IF ( SELECT ISNUMERIC ( SELECT Column1 FROM SRC ) AS help ) = 1
BEGIN
INSERT INTO DEST (ID, NAME) VALUES (45, 'TBD')
END;
ELSE
BEGIN
INSERT INTO DEST (ID, NAME) SELECT ROW_NUMBER() OVER(ORDER BY NAME) +@i, 'First';
INSERT INTO DEST (ID, NAME) SELECT ROW_NUMBER() OVER(ORDER BY NAME) +@i, 'Second';
INSERT INTO DEST (ID, NAME) SELECT ROW_NUMBER() OVER(ORDER BY NAME) +@i, 'Fourth';
END;
(simplified solution to demonstrate the purpose, it should be dynamic, not hardcoded)
.., but that obviously does not work. How to do that?
One approach you can take is the following, which uses a
CASE
statement to allow you to differentiate between numeric and non-numeric values ofColumn1
:The example will not port directly into your code, but should give you a good basis to begin working from in order to achieve your desired result.
Note my comment to your original post that you may get clashes on the
ID
column if inserting multiple rows with this. You will need to consider what to do in that situation.