2

I'm using SQL Server 2008. I'm trying to insert data into dv_user_akun table with value that I've selected from another table. Please take a look.

INSERT INTO dv_user_akun (user_id, nik, username, password, kode_tipe, flag) 
    SELECT 
        (SELECT
             CASE
                WHEN right(max(user_id), 8) IS NULL
                  THEN 'USR00000001' 
                  ELSE ('USR-' + RIGHT('0000000' + cast(right(max(user_id), 7) + 1 as nvarchar), 7)) 
             END user_id 
         FROM 
             dv_user_akun) as user_id,
        (SELECT 
             Nip, Nip, '81dc9bdb52d04dc20036dbd8313ed055', PositionCode, 1 
         FROM
             Employee 
         WHERE
             Nip NOT IN (SELECT Nik FROM dv_user_akun))

I get this error

The select list for the INSERT statement contains fewer items than the insert list.
The number of SELECT values must match the number of INSERT columns.

1 Answer 1

2

You don't have anything in your select statement. I've changed your subqueries to proper joins rather than the old style ansi joins that you have there. The only problem I still have is that you appear to be using the field Nip to insert into both nik and username fields;

INSERT INTO dv_user_akun (user_id, nik, username, password, kode_tipe, flag)
SELECT 
a.user_id
,b.Nip
,b.Nip
,b.pass
,b.PositionCode
,b.number
FROM (
        SELECT CASE 
                WHEN right(max(user_id), 8) IS NULL
                    THEN 'USR00000001'
                ELSE ('USR-' + RIGHT('0000000' + cast(right(max(user_id), 7) + 1 AS NVARCHAR), 7))
                END user_id
        FROM dv_user_akun
        ) a
CROSS JOIN
(
        SELECT 
            Nip
            ,'81dc9bdb52d04dc20036dbd8313ed055' pass
            ,PositionCode
            ,1 number
        FROM Employee
        WHERE Nip NOT IN (
                SELECT Nik
                FROM dv_user_akun
                )
        ) b
Sign up to request clarification or add additional context in comments.

1 Comment

thanks it works. you make a little mistake there SELECT ,Nip

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.