Reputation: 39298
I've got me this nice table.
create table Records (
Id uniqueidentifier primary key,
Occasion datetime not null,
Information varchar(999) default ' '
)
When I execute the first line line below, I get an error. When I execute the second, I see NULL in the cell. How should I insert stuff into the table so that the default white space kicks in?
insert into Records values (newid(), convert(varchar(21), getdate(), 121))
insert into Records values (newid(), convert(varchar(21), getdate(), 121), null)
The error message is the defaulty one but I'll put it in here anyway, in case someone asks.
Column name or number of supplied values does not match table definition.
Upvotes: 2
Views: 95
Reputation: 221370
By using the DEFAULT
keyword:
INSERT INTO Records VALUES (newid(), CONVERT(varchar(21), getdate(), 121), DEFAULT)
Or, better, by specifying the exact columns with the INSERT
statement
INSERT INTO Records (Id, Occasion)
VALUES (newid(), CONVERT(varchar(21), getdate(), 121))
Or:
INSERT INTO Records (Id, Occasion, Information)
VALUES (newid(), CONVERT(varchar(21), getdate(), 121), DEFAULT)
Why is it better?
Also interesting: SQL Column definition : default value and not null redundant?
Upvotes: 2
Reputation: 8545
insert into Records (
Id
Occasion
)
values (newid(), convert(varchar(21), getdate()), 121))
Try this.
when you don't specify column names in insert query, sql-server expects values for all the columns. that is why your first query is throwing error as you have supplied value for two columns only, whereas your second query is running correctly
Upvotes: 1
Reputation: 1632
Try this:
insert into Records values (newid(), convert(varchar(21), getdate()), 121)
You have to close the (
of convert.
Upvotes: -2