Free Newsletters:
DatabaseJournal  
DBANews
Search Database Journal:
 
HOME News MS SQL Oracle DB2 Access MySQL PostgreSQL PHP SQL Etc Scripts Links Discussion
internet.com

» HOME
» NEWS
» FEATURES
» SERIES
MS SQL
Oracle
MS Access
MySQL
DB2
» RESOURCES
Products
Scripts
Links
» DISCUSSION
» TECH JOBS

Marketplace Partners
Be a Marketplace Partner




internet.commerce
Be a Commerce Partner
KVM Switch over IP
Server Racks
SMS Gateway
Promotional Pens
Free Business Cards
Computer Deals
Prepaid Phone Card
Promotional Gifts
Memory Upgrades
KVM Switches
Dental Insurance
KVM over IP
Computer Hardware
Shop Online




All Talk, Little Action on 'Net Neutrality Front?

Compliance Issues Still Bedevil IT

Enterprise Spending On Virtualization To Rise

internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers


Linked Data Planet Conference & Expo

CA ERwin® Data Modeler Proven database design and modeling. Efficiently analyze, design and deploy effective database solutions. Whitepaper: Manage SQL Server Deployments
Try it free: CA ERwin® Data Modeler


Guide to Oracle 11g and Database Migration
Oracle Database 11g includes more features for self-management and automation, which makes it easier for customers to cost-effectively manage their data. Download this Internet.com eBook for an overview of some of the new features in 11g and for an overview of the issues you need to consider as you prepare for a database migration. »
Innovate Faster with Oracle Database 11g
Read this in-depth analysis of 56 customers, which shows significant differences between the value software vendors Oracle and SAP deliver to midsize companies. »
Oracle Business Intelligence Standard Edition One
Find out how Newport Beach, CA-based Mobilitie is shaking up the telecom industry by leveraging technology to provide an entirely different financial model for deploying, upgrading, and owning wireless and wireline network assets. »
Business Intelligence and Enterprise Performance Management: Trends for Emerging Businesses
Quickly implementing an ERP software solution can be of tremendous benefit; however, companies often struggle to balance the benefits of reducing implementation time and cost with the risks of an accelerated deployment. Read this white paper to learn about easy-to-follow best practices for achieving a successful accelerated implementation. »
Making the Case for Oracle Database on Windows
Users benefit as vendors reduce enterprise complexity and deliver integration. »

Production Manager (hands on)
Aquent
US-MA-Cambridge

Justtechjobs.com Post A Job | Post A Resume
MS SQL
October 15, 2003
T-SQL Programming Part 1 - Defining Variables, and IF...ELSE logic
By Gregory A. Larsen

This is the first of a series of articles discussing various aspects of T-SQL programming. Whether you are building a stored procedure or writing a small Query Analyzer script you will need to know the basics of T-SQL programming. This first article will discuss defining variables, and using the IF...ELSE logic.

Local Variables

As with any programming language, T-SQL allows you to define and set variables. A variable holds a single piece of information, similar to a number or a character string. Variables can be used for a number of things. Here is a list of a few common variable uses:

  • To pass parameters to stored procedures, or function
  • To control the processing of a loop
  • To test for a true or false condition in an IF statement
  • To programmatically control conditions in a WHERE statement

In SQL Server a variable is typical known as a local variable, due the scope of the variable. The scope of a local variable is only available in the batch, stored procedure or code block in which it is defined. A local variable is defined using the T-SQL "DECLARE" statement. The name of the local variable needs to start with a "@" sign as the first character of its name. A local variable can be declared as any system or user defined data type. Here is a typical declaration for an integer variable named @CNT:

	DECLARE @CNT INT

More than one variable can be defined with a single DECLARE statement. To define multiple variables, with a single DECLARE statement, you separate each variable definition with a comma, like so:

	DECLARE @CNT INT, @X INT, @Y INT, @Z CHAR(10)

Above I have defined 4 local variables with a single DECLARE statement. A local variable is initially assigned a NULL value. A value can be assigned to a local variable by using the SET or SELECT statement. On the SET command you specify the local variable and the value you wish to assign to the local variable. Here is an example of where I have defined my @CNT variable and then initialize the variable to 1.

	DECLARE @CNT INT
	SET @CNT = 1

Here is an example of how to use the SELECT statement to set the value of a local variable.

	DECLARE @ROWCNT int
	SELECT @ROWCNT=COUNT(*) FROM pubs.dbo.authors

The above example sets the variable @ROWCNT to the number of rows in the pubs.dbo.authors table.

One of the uses of a variable is to programmatically control the records returned from a SELECT statement. You do this by using a variable in the WHERE clause. Here is an example that returns all the Customers records in the Northwind database where the Customers Country column is equal to 'Germany'

	Declare @Country varchar(25) 
	set @Country = 'Germany'
	select CompanyName from Northwind.dbo.Customers
	where Country = @Country

IF ... ELSE

T-SQL has the "IF" statement to help with allowing different code to be executed based on the results of a condition. The "IF" statement allows a T-SQL programmer to selectively execute a single line or block of code based upon a Boolean condition. There are two formats for the "IF" statement, both are shown below:

Format one: IF <condition> <then code to be executed when condition true>

Format two: IF <condition> <then code to be executed when condition true>
                     ELSE < else code to be executed when condition is false>

In both of these formats, the <condition> is a Boolean expression or series of Boolean expressions that evaluate to true or false. If the condition evaluates to true, then the "then code" is executed. For format two, if the condition is false, then the "else code" is executed. If there is a false condition when using format one, then the next line following the IF statement is executed, since no else condition exists. The code to be executed can be a single TSQL statement or a block of code. If a block of code is used then it will need to be enclosed in a BEGIN and END statement.

Let's review how "Format one" works. This first example will show how the IF statement would look to execute a single statement, if the condition is true. Here I will test whether a variable is set to a specific value. If the variable is set to a specific value, then I print out the appropriate message.

	Declare @x int
	set @x = 29
	if @x = 29 print 'The number is 29'
	if @x = 30 print 'The number is 30'

The above code prints out only the phrase "The number is 29", because the first IF statement evaluates to true. Since the second IF is false the second print statement is not executed.

Now the condition statement can also contain a SELECT statement. The SELECT statement will need to return value or set of values that can be tested. If a SELECT statement is used the statement needs to be enclosed in parentheses.

	if (select count(*) from Pubs.dbo.Authors
	        where au_lname like '[A-D]%') > 0 
	   print 'Found A-D Authors'

Here I printed the message "Found A-D Authors" if the SELECT statement found any authors in the pubs.dbo.authors table that had a last name that started with an A, B, C, or D.

So far my two examples only showed how to execute a single T-SQL statement if the condition is true. T-SQL allows you to execute a block of code as well. A code block is created by using a "BEGIN" statement before the first line of code in the code block, and an "END" statement after that last line of code in the code block. Here is any example that executes a code block when the IF statement condition evaluates to true.

	if db_name() = 'master' 
	  begin
	    Print 'We are in the Master Database'
	    Print ''
	    Print 'So be careful what you execute'
	  End

Above a series of "PRINT" statements will be executed if this IF statement is run in the context of the master database. If the context is some other database then the print statements are not executed.

Sometimes you want to not only execute some code when you have a true condition, but also want to execute a different set of T-SQL statements when you have a false condition. If this is your requirement then you will need to use the IF...ELSE construct, that I called format two above. With this format, if the condition is true then the statement or block of code following the IF clause is executed, but if the condition evaluates to false then the statement or block of code following the ELSE clause will be executed. Let's go through a couple of examples.

For the first example let's say you need to determine whether to update or add a record to the Customers table in the Northwind database. The decision is based on whether the customer exists in the Northwind.dbo.Customers table. Here is the T-SQL code to perform this existence test for two different CustomerId's.

	if exists(select * from Northwind.dbo.Customers 
	            where CustomerId = 'ALFKI')
	    Print 'Need to update Customer Record ALFKI'
	else
	    Print 'Need to add Customer Record ALFKI'
	
	if exists(select * from Northwind.dbo.Customers 
	            where CustomerId = 'LARSE')
	    Print 'Need to update Customer Record LARSE'
	else
	    Print 'Need to add Customer Record LARSE'

The first IF...ELSE logic checks to see it CustomerId 'ALFKI' exists. If it exists it prints the message "Need to update Customer Record", if it doesn't exist the "Need to add Customer Record" is displayed. This logic is repeated for CustomerId = 'LARS'. When I run this code against my Northwind database I get the following output.

	Need to update Customer Record ALFKI
	Need to add Customer Record LARSE

As you can see from the results CustomerId 'ALFKI' existed, because the first print statement following the first IF statement was executed. Where as in the second IF statement CustomerId 'LARSE' was not found because the ELSE portion of the IF...ELSE statement was executed.

If you have complicated logic that needs to be performed prior to determining what T-SQL statements to execute you can either use multiple conditions on a single IF statement, or nest your IF statements. Here is a script that determines if the scope of the query is in the 'Northwind' database and if the "Customers" table exists. I have written this query two different ways, one with multiple conditions on a single IF statement, and the other by having nested IF statements.

	-- Single IF Statement with multiple conditions
	use Northwind
	if db_name() = 'Northwind' and 
	   (select count(*) from sysobjects   
	      where name = 'Customers') = 1
	  print 'Table Customers Exist'
	else 
	  print 'Not in the Northwind database' + 
	        ' or Table Customer does not exist'
	
	-- Nested IF Statements
	use Northwind
	if db_name() = 'Northwind' 
	   if (select count(*) from sysobjects 
	         where name = 'Customers') = 1
	     print 'Table Customers Exist'
	   else
	     print 'Table Customer does not exist'
	else 
	  print 'Not in the Northwind Database'

As you can see I tested to see if the query was being run from the Northwind database and whether the "Customers" table can be found in sysobjects. If this was true, I printed the message "Table Customers Exists". In the first example I had multiple conditions in a single IF statement. Since I was not able to determine which parts of the conditions in the IF statement where false the ELSE portion printed the message "Not in Northwind database or Table Customer does not exist". Now in the second example where I had a nested IF statement I was able to determine whether I was in the wrong database or the object "Customers" did not exist. This allowed me to have two separate print statements to reflect exactly what condition was getting a false value.

Conclusion


I hope that this article has helped you understand how to declare and use local variables, as well as IF...ELSE logic. Local variables are useful to hold the pieces of information related to your programming process. Where as the IF statement helps control the flow of your program so different sections of code can be executed depending on a particular set of conditions. As you can see nesting IF statements and/or having multiple conditions on an IF statement allows you to further refine your logic flow to meet your programming requirements. My next article in this T-SQL programming series will discuss how to build a programming loop.

» See All Articles by Columnist Gregory A. Larsen

Tools:
Add databasejournal.com to your favorites
Add databasejournal.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed

MS SQL Archives

Five Trends for Application Development. Download Your Complimentary Report. Exclusive. Act Now.
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers. Sponsored by HP, Citrix, and Intel.
HP eBook: Using Business Service Management (BSM) to Manage Your Business Applications
Best Practices: Make the Case for IT Investments. Complimentary Independent Report. Download Now!
Five Trends for Application Development & Program Management. Download Complimentary Report Now.


Latest Forum Threads
MS SQL Forum
Topic By Replies Updated
Mssql Equivalent Of Mysql "merge" Storage Engine dbnewbie 2 May 14th, 04:49 PM
How To Transfer Access Data Records To SQL ?? ankurdjariwala 1 May 8th, 12:24 PM
problem with federated server linking majidkhan 1 April 29th, 10:00 AM
"SELECT rowguidcol" from tables on linked servers? brentbordelon 1 April 25th, 04:12 PM







JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Microsoft Article: 7.0, Microsoft's Lucky Version?
Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Windows Server 2008
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES