简体   繁体   中英

In SQL, is it possible to use a dummy column in an insert statement?

So I have some insertion:

insert into table (col1, col2, dummy, col3) values (1,1,1,1), (2,2,2,2)

The "dummy" column doesn't really exist, it's needed because I generate the insert statement, even the column header, and some columns need to be ignored based on situation, but the data are still the same, it would make my life a lot easier if I don't need to mess with the data and just the header.

So I guess to put it another way: Is it possible to "ignore" a column on insert statement.


To put it in another another way, I am trying to do a insert statement on 3 columns with 4 columns worth of data, and is wondering if there is any way to deal with this at the SQL level instead of at the code logic level.


So here is a longer example, I have this 2D array.

{ {101,102,103,104}, {201,202,203,204}, ... }

I have a table with the following columns

col1, col2, col3, col4

Now one user says:

"I would like to only use col1, col2, col4"

And another user says:

"I would like to only use col2, col3"

How do I do this if I do not want to mess with the 2D data array?

insert into table (col1, col2, ignore, col4) 
    values (101,102,103,104), (201,202,203,204)


insert into table (ignore, col2, col3, ignore) 
    values (101,102,103,104), (201,202,203,204)

Notice that the order matters.

This sounds like a preety crazy requirement but there is a way to make it work.

With a table t which has 3 columns (a,b,c) , you can use the tables value constructor, available in SQL-Server 2008 and above. Note how you can change which columns of the input will be inserted into the table by altering only one line of the SQL code:

INSERT INTO t 
  (a, b, c) 
SELECT 
  col1, col3, col4            -- this is the only line needs configured
                              -- col2 is ignored
FROM 
  ( VALUES
    ( 1, 2, 3, 4), 
    (11,12,13,14),
    (21,22,23,24),
    (31,21,33,34)
   ) AS x 
     (col1, col2, col3, col4)
;

Tested at SQL-Fiddle

If the table has 4 columns (a,b,c,d) - as many as the value list - a similar approach would be:

INSERT INTO t 
  (a, b, c, d) 
SELECT 
  col1, NULL, col3, col4         -- this is the only line needs configured
                                 -- col2 is ignored and NULLs are put
                                 -- into column "b"
FROM         --- rest of the code is the same

Is it possible to "ignore" a column on insert statement.

Yes, don't include it in the fields list. For example:

insert into table (col1, col2, col3)

will only insert values into col1 , col2 , col3 and will leave the remainder of the columns (in the new row) with their default values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM