简体   繁体   中英

SQL Query add default value

I have an SQL query that is a load of +1000 records to a table. We have added a new field to discriminate a certain value and I need to add it to the query. Is there any command that automates the process? It would add a default value at the end of all insert.

Update:The field already has a default value of 0. The query with these inserts must specify that field to 1. I need a way to add that default value to those specific inserts.

Update2:The query type is INSERT INTO xx(xx,xx,x,x,x,x) VALUES (x,x,x,x), (x,xx,x,x,x), ----> add new value at the end

Update 3:The answers are not valid since I have more than 1000 insertions, I cannot manually add that field

You can change the default value before an after the inserts:

alter table t alter col set default = 1;

Then change it back or drop it afterwards:

alter table t alter col set default = 0;
alter table t alter col drop default;

You won't have to modify the insert statements, unless the column is already part of them (because an explicit value would override the default).

You can either set 'Default' value for that column in your table. If it is a Boolean, set default expression to False or True. Similarly works for char or integer or timestamp.

But, if you want to set it only via Query for some reason, just add that value to the query. Why not!

Example Query:

    INSERT INTO tab(c1,c2,...descriminate_column) VALUES(v1,v2,...FALSE)

or

    INSERT INTO tab(c1,c2,...descriminate_column) VALUES(v1,v2,...NULL)

or

    INSERT INTO tab(c1,c2,...descriminate_column) VALUES(v1,v2,...'default_val')

UPDATE AS PER YOUR UPDATED QUESTION:

As I understood from your update, you have a Boolean column with default False, and you want to set that column to True only for some of the Inserts in a loop and you want to include the column name for all queries. If that's the case, you can use the below query to insert default value:

INSERT INTO tab(c1, c2, c3, c4, discriminate_column) VALUES(204, 'test', '1.2.2.3', 'today', default)

UPDATE2:

INSERT INTO xx(xx,xx,x,x,x,x) VALUES (x,x,x,x), (x,xx,x,x,x)

No of columns mentioned and number of values should always be equal. If you want to leave the default values for some queries, put default for that insert.

INSERT INTO xx(xx,xx,x,x,x,x) VALUES (x,x,x,x,default), (x,xx,x,x,x)

If it's an insert...select :

insert into MyTable (col1, col2, ..., thenewcolumn)
select column1, column2, ..., 1
from somewhere

If it's a regular insert, just put 1 into the value:

insert into MyTable (col1, col2, ..., thenewcolumn)
values
(12, 'abc',...,1)

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