How to Insert Data Into a Table in SQL Server

Once you have created your table, the next step is to insert data into it. The basic syntax to insert a single row is:

INSERT INTO dbo.BRIAN (a, b) VALUES (1, 21);

This inserts one record into the BRIAN table, setting column a to 1 and column b to 21.

Inserting Multiple Rows Efficiently

Instead of writing many separate INSERT statements like this:

INSERT INTO dbo.BRIAN (a, b) VALUES (1, 21);
INSERT INTO dbo.BRIAN (a, b) VALUES (39, 21);
INSERT INTO dbo.BRIAN (a, b) VALUES (1998, 2001);
-- and so on

You can insert multiple rows with one statement like this:

INSERT INTO dbo.BRIAN (a, b) VALUES
  (1, 21),
  (39, 21),
  (1998, 2001),
  (26, 2817),
  (21, 2938),
  (12, 21),
  (3939, 4848);

This is cleaner, more efficient, and easier to maintain.

Inserting Multiple Rows Using a Loop (T-SQL)

Sometimes you might want to insert many rows dynamically, for example, inside a stored procedure or a script, or generate test data. You can do this with a loop using T-SQL's WHILE:

DECLARE @i INT = 1;

WHILE @i <= 10
BEGIN
    INSERT INTO dbo.BRIAN (a, b) VALUES (@i, @i * 10);
    SET @i = @i + 1;
END

This will insert 10 rows where column a contains values 1 through 10, and column b contains values 10 through 100 (multiples of 10).

Summary

  • Use INSERT INTO ... VALUES ... to add data.
  • Insert multiple rows with a single INSERT by separating each row with commas.
  • Use T-SQL loops (WHILE) for dynamic or repetitive inserts.

If you want, I can help you with sample scripts for bulk inserts, or inserting data from another table using INSERT INTO ... SELECT. Just ask!

Comments

Popular posts from this blog

Free Monthly Budget Spreadsheet (UK-Friendly)

Financial Literacy and ADHD – Money, Mistakes, and Learning the Hard Way