Mike
Mike

Reputation: 1067

How to insert a null value to the database?

My query doesn't work. It says there is a syntax error near null keyword. I dont know how to fix it. I want to insert an empty string or null to the database. How can i do it?
This is my query

insert into [REMARKS]
values((SELECT top 1 ref_no
FROM A_MASTER order by ref_no desc ), (SELECT top 1 current_dept
FROM A_MASTER order by ref_no desc ),'630590', GETDATE()), NULL

Inner queries work without any error.

Upvotes: 2

Views: 581

Answers (4)

Shushil Bohara
Shushil Bohara

Reputation: 5656

Why should we insert NULL in the column if that is nullable and not defined any default value then we simply ignore that column in insertion then it will automatically save null

INSERT INTO [remarks] (ref_no, current_dept) 
SELECT TOP 1 ref_no, 
         current_dept 
FROM   a_master 
ORDER  BY ref_no DESC

Just mention column definition in the insertion where you want to insert not null value and select the required values for those columns only and don't include the column where you want NULL value.

Upvotes: 0

K.K
K.K

Reputation: 366

You miss placed your close brackets,it should be i like this..

 insert into [REMARKS]
 values((SELECT top 1 ref_no
 FROM A_MASTER order by ref_no desc ), (SELECT top 1 current_dept
 FROM A_MASTER order by ref_no desc ),'630590', GETDATE(), NULL)

in Your query u referred same table twice for two column.

You can write like..

 insert into [REMARKS] select top 1 ref_no,curent_dept 
 '630590',GETDATE(),NULL 
 from A_MASTER 
 order By ref_no desc

Since both the columns are from same table..

Upvotes: 2

Pரதீப்
Pரதீப்

Reputation: 93754

You have miss placed close parenthesis but here is the correct way to insert

INSERT INTO [remarks] 
            (ref_no, 
             current_dept, 
             third_col) 
SELECT TOP 1 ref_no, 
             current_dept, 
             NULL 
FROM   a_master 
ORDER  BY ref_no DESC 

Note: Always add insert column list during insertion

Upvotes: 2

Mike
Mike

Reputation: 1067

I found the mistake. The reason is i have added the NULL keyword after the close paranthesis of the insert query. When i added inside the paranthesis it works.

insert into [REMARKS]
values((SELECT top 1 ref_no
FROM A_MASTER order by ref_no desc ), (SELECT top 1 current_dept
FROM A_MASTER order by ref_no desc ),'630590', GETDATE(),null)

Upvotes: 0

Related Questions