To insert data into a table in SQL Server Management Studio, you can use the following sample insert code.‚ I have included my notes on how the functions work using comments prefaced by — in the SQL.
–I have created a simple table for us to work with below:
create table Calendar
dateid int NOT NULL Primary Key identity(1,1),
month int NOT NULL constraint CK_zeroTOtwelve Check(month > 0 AND 12 > month),
date int NOT NULL constraint CK_zeroTOthirty Check(date > 0 AND 31 > DATE),
hour int NOT NULL constraint CK_zeroTOtwentyfour Check(hour > 0 and 25 > hour)
–The actual code for inserting data into the Calendar table we created above is as follow:
insert into calendar
(month, date, hour) –state which columns are going to be inserted into.‚ Dateid updates itself.
Values (3,31,12)‚ ‚ –the actual values to be inserted into the table.
The sample insert above is one of the simplest and most direct ways to place data into a SQL table.‚ However, in real applications you will almost always declare variables instead of actually stating the values you wish to insert to the SQL table. My next example shows how you can declare variables and create a simple stored procedure that can be used by applications to insert data:
USE [FinalProject] –The database you wish the SQL stored procedure to use.
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
Create proc [dbo].[AddUser] –Creates the stored procedure and names it AddUser
(@Email varchar(50), –declares the variables to be used and their data types.
Insert into Users (First, Last, Email)–Insert Statement
Values (@First, @Last, @Email) –Values you wish to insert.