SQL Server snippets

How to ADD COLUMN to existing TABLE

Example 1

Let's suppose we have a #Food table and we want to ADD a column named Price.

CREATE TABLE #Food(
	[Code] [nvarchar](50) NOT NULL,
	[Group] [nvarchar](100) NULL,
	[Quantity] [int] NOT NULL,
	[Color] [nvarchar](50) NULL,
) ON [PRIMARY];
INSERT INTO #Food
  ( [Code], [Group], [Quantity],[Color] )
VALUES
  ('Apple', 'Fruit', 44, 'red'),
  ('Apple', 'Fruit', 1, 'yellow'),
  ('Pineapple', 'Fruit', 14, 'brown'),
  ('Apple', 'Fruit', 12, 'red'),
  ('Banana', 'Fruit', 1, 'yellow'),
  ('Tomatoes', 'Vegetables', 8, 'red'),
  ('Cucumbers', 'Vegetables', 3, 'green');
Food table pre add column

ALTER TABLE #Food
ADD Price decimal(10,3) NOT NULL DEFAULT(0)
Food table post add column

You can find an interactive version of this example following this link .

Back to SQL Server cookbook page