Sunday, August 4, 2013

Insert default values for all columns in table - SQL Server

I was asked by some of the job colleagues as how can insert all the DEFAULT values in table when table have all the columns defined with default property. If the table has at least one column without default and identity column, then we can do insert default with rest columns easily. How can with insert default values for all columns in the table? For that we will see a small demo where we will create one table with all columns defined by default and will see the insertion of default values for the same. 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
USE DEMO
GO
-- Creating table
IF (OBJECT_ID('DefaultTable','U') > 0)
DROP TABLE DefaultTable
GO
CREATE TABLE DefaultTable
(
 TransactionId INT IDENTITY(1,1) NOT NULL,
 TransactionName VARCHAR(100) NOT NULL DEFAULT 'Test Transaction',
 TransactionDate DATETIME NOT NULL DEFAULT GETDATE(),
 TransactionType SMALLINT NOT NULL DEFAULT 0
)
GO
-- Insert Default values for all columns
INSERT DefaultTable
DEFAULT VALUES
GO
-- Reviewing records in table
SELECT
*
FROM DefaultTable
GO

Let us try more with some more inserts and see again,
?
1
2
3
4
5
6
7
8
9
INSERT DefaultTable
DEFAULT VALUES
GO 100
-- Reviewing records in table
SELECT
*
FROM DefaultTable
GO

You might experience this type of need.