How to insert into a table that specifies a DEFAULT value for every column? - sql

I have a table where all columns are auto-populated whenever an insertion happens:
CREATE TABLE …
(
ItemID INT NOT NULL IDENTITY(…),
DateCreated DATETIME2 NOT NULL DEFAULT GETDATE()
);
How do I write a SQL statement that inserts a new row into this table without having to manually provide any concrete values to insert?
(There is already a similar question, but it differs in that it's about a table with some non-DEFAULT columns for which a value must be manually provided.)

Use the DEFAULT VALUES option:
INSERT INTO IdentitySpecification
DEFAULT VALUES;

Related

Possible to assign a default value on a NULL against table column in sql

I am wondering if there is a way that when creating a table that you can assign a default value to a column if the value is null.
I understand that you can use the syntax DEFAULT however this is only for when the value is absent. Is there a way similar to this that you can say when NULL it will add the default without using a trigger.
CREATE TABLE DBO.TESTS
(
TEST VARCHAR(100) DEFAULT(ISNULL('test',NULL)),
NUM INT
)
This is a test and the kind of thing i was looking at?
UPDATE:
Example input
INSERT INTO TESTS (TEST,NUM)
VALUES (NULL,1)
Where the "NULL" is i would like that to enter the value "test". But also if i was to do the following
INSERT INTO TESTS (NUM)
VALUES (1)
This would also enter the value of "test" into the column "TEST".
I hope this helps.
Yes, there is a way to do what you want. It is called a trigger. You would have to define a trigger that sets the value when a NULL is inserted into the column.
If you use an INSTEAD OF trigger, then you can still declare the column as NOT NULL. The trigger will take care of assigning a value so the constraint is not violated.
So, you can do this. Why you would want to do it is another question. Perhaps you are not familiar with the DEFAULT keyword that allows default values to be inserted using a VALUES() clause. This is explained in the documentation for INSERT.
You can add a default constraint to your table which will automatically add a set value for the column if the insert does not have a value for it:
CREATE TABLE DBO.TESTS
(
TEST VARCHAR(100),
NUM INT
)
ALTER TABLE [DBO].[TESTS] ADD CONSTRAINT [DF_TESTS_TEST] DEFAULT (N'default_value_goes_here') FOR [TEST]
INSERT INTO [DBO].[TESTS] VALUES (NULL, 1)
INSERT INTO [DBO].[TESTS] (num) VALUES (2)
Results
NULL 1
'default_value_goes_here' 2
If you want to check during an insert you can use COALESCE
DECLARE #insertValue VARCHAR(100)
SET #insertValue = NULL
INSERT INTO DBO.TESTS VALUES (COALESCE (#insertValue, 'defaultValue'), 1);
The bottom line is that the column should be non-nullable with a default value.
It's possible to replace null values with default values in a trigger for insert/update, but that doesn't make any sense - first because it means every update/insert will have to do that extra work, and second, because that would make it impossible to insert null to the column (unless the triggers are disabled) so why allow nulls in the first place? It's a mistake that will only be confusing for anyone attempting to use that table.
Think about it from the user side - when you send null to a nullable column, you expect it to be null, you don't expect it to contain a value.
If you run this insert statement:
INSERT INTO TESTS (TEST,NUM)
VALUES (NULL,1)
You expect the table to contain a row where Test is null and num = 1.
You do not expect the Test column to contain the default value.
When providing a value for a column, including NULL, that value will be used. NULL is still a value, just an unknown value. A DEFAULT value will only be used if no value is passed (which, as I just said, NULL is a value so doesn't count).
If you don't want a NULL in your table, then instead stop people supplying them by setting your column as NOT NULL:
CREATE TABLE dbo.TestTable (ID int, String varchar(100) NOT NULL DEFAULT 'test')
GO
--INSERT is successful, String has a value of 'test'
INSERT INTO dbo.TestTable (ID)
VALUES(1);
GO
--INSERT fails, String cannot have a value of NULL
INSERT INTO dbo.TestTable (ID,
String)
VALUES(2,NULL);
GO
SELECT *
FROM dbo.TestTable;
GO
DROP TABLE dbo.TestTable;
GO

SQL Server Insert with no specified columns

I have a table with an auto-generated ID column (and that's all!)
CREATE TABLE [dbo].[EmailGroup](
[EmailGroupGuid] [uniqueidentifier] NOT NULL
CONSTRAINT [PK_EmailGroup] PRIMARY KEY CLUSTERED ([EmailGroupGuid] ASC)
) ON [PRIMARY]
ALTER TABLE [dbo].[EmailGroup]
ADD CONSTRAINT [DF_EmailGroup_EmailGroupGuid] DEFAULT (newsequentialid()) FOR [EmailGroupGuid]
I want to INSERT into this table and extract the generated ID. but, I can't work out if it's possible. It seems to complain about the lack of values/columns.
DECLARE #Id TABLE (Id UNIQUEIDENTIFIER)
INSERT INTO EmailGroup
OUTPUT inserted.EmailGroupID INTO #Id
Is there any way to do this? I mean I could add a dummy column to the table and easily do this:
INSERT INTO EmailGroup (Dummy)
OUTPUT inserted.EmailGroupID INTO #Id
VALUES (1)
however I don't really want to.
I could also specify my own ID and insert that, but again, I don't really want to.
Though I'm not sure why would you need such a table, the answer to your question is to use the keyword DEFAULT:
INSERT INTO EmailGroup (EmailGroupGuid)
OUTPUT inserted.EmailGroupGuid INTO #Id
VALUES(DEFAULT);
Another option is to use DEFAULT VALUES, as shown in Pawan Kumar's answer.
The key difference between these two options is that specifying the columns list and using the keyword default gives you more control.
It doesn't seem much when the table have a single column, but if you will add columns to the table, and want to insert specific values to them, using default values will no longer be a valid option.
From Microsoft Docs on INSERT (Transact-SQL):
DEFAULT
Forces the Database Engine to load the default value defined for a column.
If a default does not exist for the column and the column allows null values, NULL is inserted.
For a column defined with the timestamp data type, the next timestamp value is inserted.
DEFAULT is not valid for an identity column.
DEFAULT VALUES
Forces the new row to contain the default values defined for each column.
So as you can see, default is column based, while default values is row based.
Please use this.
CREATE TABLE [dbo].[EmailGroup]
(
[EmailGroupGuid] [uniqueidentifier] NOT NULL CONSTRAINT [PK_EmailGroup] PRIMARY KEY CLUSTERED ([EmailGroupGuid] ASC)
) ON [PRIMARY]
ALTER TABLE [dbo].[EmailGroup]
ADD CONSTRAINT [DF_EmailGroup_EmailGroupGuid] DEFAULT (newsequentialid()) FOR [EmailGroupGuid]
DECLARE #Id TABLE (Id UNIQUEIDENTIFIER)
INSERT INTO EmailGroup
OUTPUT inserted.EmailGroupGuid INTO #Id DEFAULT VALUES
SELECT * FROM #Id
last 3 OUTPUTs from my Laptop
--92832040-7D52-E811-B049-68F728AE8695
--2B6ADC5F-7D52-E811-B049-68F728AE8695
--0140AF66-7D52-E811-B049-68F728AE8695

Can not add a column to existing table

I have a table viz. expenses with three columns as under
ExpenseId int NOT NULL,
ExpenseName varchar(50) NOT NULL,
Invalid bit NOT NULL
To add a new column (OldCode char(4) not null), I used design feature for tables in Microsoft SQL Server Management Studio. But I get following error
'Expenses' table
- Unable to modify table. Cannot insert the value NULL into column 'OldCode', table 'TransportSystemMaster.dbo.Tmp_Expenses'; column does not allow nulls. INSERT fails. The statement has been terminated.
Incidentally I have been able to add same column with same specifications to other tables of the same database.
Any help?
Your Table Consist of Existing Records
and you are pushing a new column of type NOT NULL.
so for older records the data have to be something.
try something like this
ALTER TABLE MY_TABLE ADD Column_name INT NULL
GO
UPDATE MY_TABLE <set valid not null values for your column>
GO
ALTER TABLE MY_TABLE ALTER COLUMN Column_name INT NOT NULL
GO
Since OldCode is NOT NULL, you should specify a default value for it.
when you have some rows on your table you can't add a column that is not nullable you should provide a default value for it
Alter Table table_name add OldCode int not null DEFAULT(0);
You have to specify values for all the 4 fields of the table, its purely because, while designing the table you set the definition of the columns to be not null. Again you are adding a new column called OldCode and setting to be not null, all ready existing records hasn't got a value. So that is the reason its complains

Can I add a not null column without DEFAULT value

Can I add a column which is I specify as NOT NULL,I don't want to specify the DEFAULT value but MS-SQL 2005 says:
ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'test' cannot be added to non-empty table 'shiplist' because it does not satisfy these conditions.
If YES, please let me know the syntax, if No please specify the reason.
No, you can't.
Because if you could, SQL wouldn't know what to put as value in the already existing records. If you didn't have any records in the table it would work without issues.
The simplest way to do this is create the column with a default and then remove the default.
ALTER TABLE dbo.MyTable ADD
MyColumn text NOT NULL CONSTRAINT DF_MyTable_MyColumn DEFAULT 'defaultValue'
ALTER TABLE dbo.MyTable
DROP CONSTRAINT DF_MyTable_MyColumn
Another alternative would be to add the column without the constraint, fill the values for all cells and add the constraint.
Add the column to the table, update the existing rows so none of them are null, and then add a "not null" constraint.
No - SQL Server quite reasonably rejects this, because it wouldn't know what value existing rows should have
It's easy to create a DEFAULT at the same time, and then immediately drop it.
I use this approach to insert NOT NULL column without default value
ALTER TABLE [Table] ADD [Column] INT NULL
GO
UPDATE [Table] SET [Column] = <default_value>
ALTER TABLE [Table] ALTER COLUMN [Column] INT NOT NULL
No.
Just use empty string '' (in case of character type) or 0 (if numeric), etc as DEFAULT value
No you cannot. But you can consider to specify the default value to ('')
No, you can't, as SQL Server, or any other database engines will force this new column to be null for existing rows into your data table. But since you do not allow a NULL, you are required to provide a default value in order to respect your own constraint. This falls under great sense! The DBE will not extrapolate a value for non-null values for the existing rows.
#Damien_The_Unbeliever's comment ,
Is it adding computed column? Neither question nor answer implied anything like that. In case of computed column the error states:
"Only UNIQUE or PRIMARY KEY constraints can be created on computed columns, while CHECK, FOREIGN KEY, and NOT NULL constraints require that computed columns be persisted"
OK, if to continue this guessing game, here is my script illustrating the adding of "NOT NULL" column in one "ALTER TABLE" step:
CREATE TABLE TestInsertComputedColumn
(
FirstName VARCHAR(100),
LastName CHAR(50)
);
insert into TestInsertComputedColumn(FirstName,LastName)
select 'v', 'gv8';
select * from TestInsertComputedColumn;
ALTER TABLE TestInsertComputedColumn
ADD FullName As FirstName + LastName PERSISTED NOT NULL;
select * from TestInsertComputedColumn;
--drop TABLE TestInsertComputedColumn;
I used below approach it worked for me
Syntax:
ALTER TABLE <YourTable> ADD <NewColumn> <NewColumnType> NOT NULL DEFAULT <DefaultValue>
Example:
ALTER TABLE Tablename ADD ColumnName datetime NOT NULL DEFAULT GETDATE();
As an option you can initially create Null-able column, then update your table column with valid not null values and finally ALTER column to set NOT NULL constraint:
ALTER TABLE MY_TABLE ADD STAGE INT NULL
GO
UPDATE MY_TABLE SET <a valid not null values for your column>
GO
ALTER TABLE MY_TABLE ALTER COLUMN STAGE INT NOT NULL
GO

How to INSERT INTO table DEFAULT VALUES

When you want to insert default values into a table, some databases allow this syntax:
INSERT INTO table DEFAULT VALUES;
ASE does not support this.
Using:
INSERT INTO table (col2, col3)
VALUES (DEFAULT, DEFAULT)
and skipping the identity column works for columns with constant default values, but not for computed columns including timestamp.
Introspecting the table for a column with a constant default and then just specifying DEFAULT for that column would work, unless it's a table with only an identity and computed columns, but no one is likely to use such tables.
Is there an easier way?
Skip columns with default values from the insert statement.
If a default value exists for the skipped column (or user-defined datatype of the column), it is entered.