Quote:
I want a column to default to 'None Reported' when new records are created.
Q1 How can I do this?
|
Consider using char, varchar, nchar, nvarchar columns for character data (text columns are more appropriate for very large character data >> 4000 - 8000 characters).
A1 You can use Alter Table to add a default constraint to _char columns. for example:
ALTER TABLE [dbo].[YourTableName]
ADD CONSTRAINT [Default_ForYourVarCharDataColumnName] DEFAULT ('None Reported') FOR [YourVarCharDataColumnName]
To work with a detailed example run the following in tempdb:
Use TempDB
Go
CREATE TABLE [Test] (
[IDColumn] [int] IDENTITY (1, 1) NOT NULL ,
[VarCharData] [varchar] (32) NOT NULL,
[InsertedBy] [varchar] (32) NOT NULL
)
GO
SELECT [IDColumn], [VarCharData], [InsertedBy] FROM [tempdb].[dbo].[Test]
-- insert some values:
INSERT INTO [tempdb].[dbo].[Test]([VarCharData], [InsertedBy])
VALUES('Mary had a lamb.', 'Tom')
INSERT INTO [tempdb].[dbo].[Test]([VarCharData], [InsertedBy])
VALUES('The lamb had a fleece.', 'Dick')
INSERT INTO [tempdb].[dbo].[Test]([VarCharData], [InsertedBy])
VALUES('The fleece was white as snow.', 'Harry')
Go
-- the following insert should fail (no default exists for VarCharData)
INSERT INTO [tempdb].[dbo].[Test]([InsertedBy])
VALUES('Joe')
Go
-- view table rows
SELECT [IDColumn], [VarCharData], [InsertedBy] FROM [tempdb].[dbo].[Test]
-- Now add the 'None Reported' default (a constraint for the [VarCharData] column)
ALTER TABLE [dbo].[Test] ADD CONSTRAINT [Default_Test_VarCharData] DEFAULT ('None Reported') FOR [VarCharData]
Go
-- the following should now no longer fail (the default 'None Reported' should appear in the [VarCharData] column)
INSERT INTO [tempdb].[dbo].[Test]([InsertedBy])
VALUES('Joe')
Go
-- view table rows Note: (the default 'None Reported' should appear in the [VarCharData] column)
SELECT [IDColumn], [VarCharData], [InsertedBy] FROM [tempdb].[dbo].[Test]