Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

SQLStudies

My name is Kenneth Fisher and I am Senior DBA for a large (multi-national) insurance company. I have been working with databases for over 20 years starting with Clarion and Foxpro. I’ve been working with SQL Server for 12 years but have only really started “studying” the subject for the last 3. I don’t have any real "specialities" but I enjoy trouble shooting and teaching. Thus far I’ve earned by MCITP Database Administrator 2008, MCTS Database Administrator 2005, and MCTS Database Developer 2008. I’m currently studying for my MCITP Database Developer 2008 and should start in on the 2012 exams next year. My blog is at www.sqlstudies.com.

Insert into a table using only default values

A while back I talked about the DEFAULT keyword and using it to tell SQL to use the default value without having to specify an actual value. Well along that same note, what do you do if you want all of the columns to use their defaults? Or if you don’t have any columns except for an identity column? You use the DEFAULT VALUES command.

INSERT INTO TableName DEFAULT VALUES

This is particularly useful if you have a table with just an identity column. In fact to my knowledge it’s the only way to insert a row into a table like this.

CREATE TABLE IdentTable (Id int identity (1,1))
GO
INSERT INTO IdentTable DEFAULT VALUES
GO

Of course tables like that were more common back before SQL 2012 when SEQUENCES showed up.

One thing I do want to point out when using this particular command. If you haven’t specified a default constraint then the default is NULL. Why does this matter? Well if you have a column without a default constraint that doesn’t allow NULLs then the command will fail.

CREATE TABLE IdentTable2 (
	Id int identity (1,1), 
	NotNull char(10) NOT NULL)
GO
INSERT INTO IdentTable2 DEFAULT VALUES
GO

Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column ‘NotNull’, table ‘master.dbo.IdentTable2′; column does not allow nulls. INSERT fails.


Filed under: Microsoft SQL Server, SQLServerPedia Syndication, T-SQL Tagged: code language, language sql, microsoft sql server, sql statements, T-SQL

Comments

Leave a comment on the original post [sqlstudies.com, opens in a new window]

Loading comments...