Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Declare Variables / Case Logic / Display Variable 1

Status
Not open for further replies.

tqeonline

MIS
Oct 5, 2009
304
US
Hey guys i have a question.

Is there a way to in the Select statement declare variables that equal a select statement and then do case logic on that variable and depending on the case logic increment another variable.

Ex.

Code:
Declare @Variable String
Declare @Health Integer
Select [Column1], 

SET @Variable = (SELECT STATEMENT)

Case @Variable = 0 
 @Health = @Health + 1
Case @Variable = 1
 @Health = @Health + 2
End Case

@Health as 'Health'

What that does it sets a variable and then increments the health based off that variable.

- Matt

"If I must boast, I will boast of the things that show my weakness"

- Windows 2003 Server, 98 SE, XP
- VB.NET, VSTS 2010, ASP.NET, EXCEL VBA, ACCESS, SQL 2008
 
Case statements are used for data, not programming logic. It's a subtle yet important distinction.

If/else If/Else is used to control programming logic, so you could do this...

Code:
Declare @Variable String
Declare @Health Integer
Select [Column1], 

SET @Variable = (SELECT STATEMENT)

If @Variable = 0 
   Set @Health = @Health + 1
Else If @Variable = 1
   Set @Health = @Health + 2

Select @Health as 'Health'

You could also do this:

Code:
Declare @Variable String
Declare @Health Integer
Select [Column1], 

SET @Variable = (SELECT STATEMENT)

Set @Health = Case When @Variable = 0 
                        Then @Health + 1
                   When  @Variable = 1
                        Then @Health + 2
                   Else @Health
                   End

Select @Health as 'Health'

-George
Microsoft SQL Server MVP
My Blogs
SQLCop
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top