What means DEFAULT VALUES specification in an insert query? - sql

I am pretty new in Microsoft SQL Server and I am not so into DB in general.
I have the following doubt about an insert query that begin in this way:
insert into MyTable DEFAULT VALUES
What exactly mean the DEFAULT VALUES specification?
Tnx
Andrea

Reading the fine manual yields:
DEFAULT VALUES
Forces the new row to contain the default values defined for each column.

Well it uses the default values specified in your table.
So for example if you have a column CreationDate datetime default(getdate()) it will use it.

If each of the required columns in MyTable has specified DEFAULT VALUE then this statement insert such a row.
For example you could have column Date with default 01/01/2014 and position with DEFAULT 'Developer' and this statement would insert such a record.
You can read more here: http://msdn.microsoft.com/en-us/library/aa933206%28SQL.80%29.aspx

You can watch default specifications in work by checking that code:
DECLARE #tmp as table
(
id int null,
num int null default(777),
txt varchar(10) null default('abc'),
date datetime null
)
insert into #tmp DEFAULT VALUES
select * from #tmp
Output is
id num txt date
NULL 777 abc NULL

Related

Inserting missing date into non nullable Datetime field

Here we have an existing database and I'm building a new system with a new database.
There I need to transfer some data from the old database table to the new database table.
I wrote this query in the SQL
INSERT INTO [Mondo-UAT].[dbo].[Countries] (
[Country_Name]
,[Country_Code]
,[Note]
)
SELECT [Code1]
,[Code3]
,[Name]
FROM [MondoErp-UAT].[dbo].[Nations]
The issue is in the [Mondo-UAT].[dbo].[Countries] table has other columns like Note is a string and Status is a bool CreateBy is int CreateDate is DateTime . So when I run the query it returns with an error
Msg 515, Level 16, State 2, Line 8 Cannot insert the value NULL into column 'CreatedDate', table 'Mondo-UAT.dbo.Countries'; column does not allow nulls. INSERT fails. The statement has been terminated
So I wanna know how to insert data for the CreateDate,CreateBy ,Notes from the above script I wrote.
If the target table has non-nullable columns without defaults, you have to specify values for those fields when inserting data.
The easiest solution would be to modify the target table to add DEFAULT values for those fields, eg SYSDATETIME() for Created, SYSTEM_USER for CreatedBy and '' for Notes. For Status you'll have to decide what a good default status is. 0 may or may not be meaningful.
Otherwise, these values will have to be specified in the query:
INSERT INTO [Mondo-UAT].[dbo].[Countries] (
[Country_Name]
,[Country_Code]
,[Note]
, Created
, CreatedBy
, Status
)
SELECT [Code1]
,[Code3]
,[Name]
, SYSDATETIME()
, SYSTEM_USER
, 0
FROM [MondoErp-UAT].[dbo].[Nations]
SYSTEM_USER returns the login name of the current user, whether it's a Windows or SQL Server login. This makes it a good default for user columns.
SYSDATETIME returns the current time as a DATETIME2(7) value. If Created is a DATETIMEOFFSET, SYSDATETIMEOFFSET should be used.
You can set Default Value for CreateDate,CreateBy,Notes columns in the [Mondo-UAT].[dbo].[Countries] table if they are not null columns. So, When you insert data into the table and do not insert a value for these columns, the default value will be inserted.

Adding new column and set GETDATE as value in SQL Server 2017

This is my query:
alter table reseau add datemodification datetime default getdate()
After execution the rows have NULL as their value but I want them set to the current value of GETDATE().
How can do I do this?
DEFAULT is a CONSTRAINT that sets the value of a column when you omit it when performing an INSERT. If you want to then want to create a column with a DEFAULT value, and populate it at the point it with said DEFAULT value at the point of creating it then add WITH VALUES at the end of the statement:
CREATE TABLE dbo.test (ID int);
INSERT INTO dbo.Test VALUES (1),(2),(3),(4),(5);
GO
ALTER TABLE dbo.Test ADD D datetime DEFAULT GETDATE() WITH VALUES;
GO
SELECT *
FROM dbo.Test;
GO
DROP TABLE dbo.Test;
db<>fiddle
If you want to update existing values after adding the column, then use update:
update reseau
set datemodification = getdate();
The default takes effect for new rows.
Alternatively, you can define the column to be not null:
alter table reseau add datemodification not null datetime default getdate();
Then the existing rows will use the default value.
Here is a db<>fiddle, illustrating the two methods.

Select row just inserted without using IDENTITY column in SQL Server 2012

I have a bigint PK column which is NOT an identity column, because I create the number in a function using different numbers. Anyway, I am trying to save this bigint number in a parameter #InvID, then use this parameter later in the procedure.
ScopeIdentity() is not working for me, it saved Null to #InvID, I think because the column is not an identity column. Is there anyway to select the record that was just inserted by the procedure without adding an extra ID column to the table?
It would save me a lot of effort and work if there is a direct way to select this record and not adding an id column.
insert into Lab_Invoice(iID, iDate, iTotal, iIsPaid, iSource, iCreator, iShiftID, iBalanceAfter, iFileNo, iType)
values (dbo.Get_RI_ID('True'), GETDATE(),
(select FilePrice from LabSettings), 'False', #source, #user, #shiftID, #b, #fid, 'Open File Invoice');
set #invID = CAST(scope_identity() AS bigint);
P.S. dbo.Get_RI_ID('True') a function returns a bigint.
Why don't you use?
set #invId=dbo.Get_RI_ID('True');
insert into Lab_Invoice(iID,iDate,iTotal,iIsPaid,iSource,iCreator,iShiftID,iBalanceAfter,iFileNo,iType)
values(#invId,GETDATE(),(select FilePrice from LabSettings),'False',#source,#user,#shiftID,#b,#fid,'Open File Invoice');
You already know that big id value. Get it before your insert statement then use it later.
one way to get inserted statement value..it is not clear which value you are trying to get,so created some example with dummy data
create table #test
(
id int
)
declare #id table
(
id int
)
insert into #test
output inserted.id into #id
select 1
select #invID=id from #id

SQL Server 2012 sequence

I create a table and sequence in order to replace identity in the table I use SQL Server 2012 Express but I get this error while I tried to insert data to the table
Msg 11719, Level 15, State 1, Line 2
NEXT VALUE FOR function is not allowed in check constraints, default objects, computed columns,
views, user-defined functions, user-defined aggregates, user-defined
table types, sub-queries, common table expressions, or derived
tables.
T-SQL code:
insert into Job_Update_Log(log_id, update_reason, jobid)
values((select next value for Job_Log_Update_SEQ),'grammer fixing',39);
This is my table:
create table Job_Update_Log
(
log_id int primary key ,
update_reason nvarchar(100) ,
update_date date default getdate(),
jobid bigint not null,
foreign key(jobid) references jobslist(jobid)
);
and this is my sequence:
CREATE SEQUENCE [dbo].[Job_Log_Update_SEQ]
AS [int]
START WITH 1
INCREMENT BY 1
NO CACHE
GO
Just get rid of the subselect in the VALUES section, like this:
insert into Job_Update_Log(log_id,update_reason,jobid)
values (next value for Job_Log_Update_SEQ,'grammer fixing',39);
Reference: http://msdn.microsoft.com/en-us/library/hh272694%28v=vs.103%29.aspx
Your insert syntax appears to be wrong. You are attempting to use a SELECT statement inside of the VALUES section of your query. If you want to use SELECT then you will use:
insert into Job_Update_Log(log_id,update_reason,jobid)
select next value for Job_Log_Update_SEQ,'grammer fixing',39;
See SQL Fiddle with Demo
I changed the syntax from INSERT INTO VALUES to INSERT INTO ... SELECT. I used this because you are selecting the next value of the sequence.
However, if you want to use the INSERT INTO.. VALUES, you will have to remove the SELECT from the query:
insert into Job_Update_Log(log_id,update_reason,jobid)
values(next value for Job_Log_Update_SEQ,'grammer fixing',39);
See SQL Fiddle with Demo
Both of these will INSERT the record into the table.
Try this one:
–With a table
create sequence idsequence
start with 1 increment by 3
create table Products_ext
(
id int,
Name varchar(50)
);
INSERT dbo.Products_ext (Id, Name)
VALUES (NEXT VALUE FOR dbo.idsequence, ‘ProductItem’);
select * from Products_ext;
/* If you run the above statement two types, you will get the following:-
1 ProductItem
4 ProductItem
*/
drop table Products_ext;
drop sequence idsequence;
------------------------------

How to input the value 'NULL' into nvarchar column in SQL Server?

I have a requirement to insert the literal value 'NULL' into a nvarchar column as a default value. But when I insert records the default is going as db NULL instead of the literal 'NULL'. Can someone tell me where I am going wrong?
So you want the actual string of "NULL" to be inserted? Try something like this:
create table NullTable
(
nvarchar(100) not null default 'NULL',
.... -- your other fields
)
EDIT: Here is a full solution
create table InsertNull
(
Nullfield nvarchar(100) not null default 'NULL',
someint int not null
)
go
insert into insertnull(someint)
select 20
select *
from InsertNull
Note the quotes:
INSERT INTO yourtable (varcharfield) VALUES ('NULL'); // string null
INSERT INTO yourtable (varcharfield) VALUES (NULL); // actual null
If set the default in code instead of the designer is should work.
ALTER TABLE [myTable] ADD DEFAULT ('NULL') FOR [TextColumn]