Learn more about SQL Server tools

   
   























Latest from MSSQLTips















SQL Server INSERT command with variables




Overview

Variables are used as a means to assign values in code rather than hard coding values.  In simple examples, variables may seem excessive, but they are a good concept to understand as your development skills progress. 

Explanation

In this example, we are going to slightly change the first example to use variables in the INSERT command rather than hard coded values.

Let's explain what's going on with this code:

  • In the first block of code, we are declaring a variable for each column.  All of the data types for the variables match the columns.
  • In the second block of code, we are setting each of the variables to a value.  Note that the varchar and datetime columns have their values in single quotes and integer values are not in single quotes.
  • In the third block of code, this should look similar to the example above except the code in the 'VALUES' section includes the variables and not the actual values.
-- 1 - Declare variables
DECLARE @FirstName varchar(25)
DECLARE @LastName varchar(25)
DECLARE @PhoneNumber varchar(15)
DECLARE @EmailAddress varchar(25)
DECLARE @Priority int
DECLARE @CreateDate datetime

-- 2 - Initialize variables
SET @FirstName = 'Kris'
SET @LastName = 'Fierce'
SET @PhoneNumber = '222-222-2222'
SET @EmailAddress = 'kris@FierceFishing.com'
SET @Priority = 1
SET @CreateDate = '2011-09-15'

-- 3 - Execute INSERT command
INSERT INTO [dbo].[Customer]
           ([FirstName]
           ,[LastName]
           ,[PhoneNumber]
           ,[EmailAddress]
           ,[Priority]
           ,[CreateDate])
     VALUES
           (@FirstName
           ,@LastName
           ,@PhoneNumber
           ,@EmailAddress
           ,@Priority
           ,@CreateDate)
GO






 
Sponsor Information







 

Follow

Get Free SQL Tips

Twitter

LinkedIn

Google+

Facebook

Pinterest

RSS

Learning

DBAs

Developers

BI Professionals

Careers

Q and A

Today's Tip

Resources

Tutorials

Webcasts

Whitepapers

Tools

Search

Tip Categories

Search By TipID

Authors

Community

First Timer?

Pictures

Free T-shirt

Contribute

Events

User Groups

Author of the Year

More Info

Join

About

Copyright

Privacy

Disclaimer

Feedback

Advertise

Copyright (c) 2006-2015 Edgewood Solutions, LLC All rights reserved
Some names and products listed are the registered trademarks of their respective owners.