Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert NULL and DEFAULT values with an INSERT/SELECT statement

Tags:

sql-server

In MICROSOFT SQL SERVER have the following table:

CREATE TABLE [T1]
(
    [ID] int IDENTITY (1, 1) NOT NULL,
    [col1] int NOT NULL,
    [col2] int NOT NULL,
    [col3] int NULL,
    [col4] datetime NOT NULL DEFAULT (getdate()),
    [col5] datetime NOT NULL DEFAULT (getdate())
)

I want to write an insert statement that select 2 columns from another table and insert all the other column as NULL or default. This is what I have tried so far (but it doesn't work):

    INSERT INTO [T1] ([col1],[col2], [COL3])
SELECT [1column],[2column],NULL
FROM [T2]

When I right click on T1 table and select open table the table has only 2 columns, even if in the columns "folder" in object explorer there are all the columns

What I want to achieve is to have in T1: in Col1 and COL2 the result of the SELECT and in COL3 NULL and in COL4 and COL5 the default value!


1 Answers

INSERT INTO [T1] ([col1], [col2], [COL3])
SELECT [1column],[2column],NULL
FROM [T2]

This should work fine, just checked:

INSERT
INTO    [T1] ([col1], [col2], [col3])
SELECT  1, 2, NULL

SELECT  *
FROM    [T1]

id    col1  col2  col3  col4                     col5
---   ---   ---   ---   ---                      ---
1     1     2     NULL  2009-04-22 15:46:47.090  2009-04-22 15:46:47.090

What's the exact error you are receiving?

like image 88
Quassnoi Avatar answered Oct 20 '25 11:10

Quassnoi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!