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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I use if statements in SQL

Status
Not open for further replies.

dylan42

Programmer
Apr 16, 2008
4
GB

I want to check a field and if this field contains value then move this value to s field in the table and update.
I would like to build this in BEGIN .... END And incorprate an IF .. How do I do it ?????/

e.g name1 in table called NAMES
newname - a variable in the script

If newname=blanks
move newname to name1 .
UPDATE NAMES


THankyou
 
You want WHERE

Code:
update names
set name1 = newname
where newname = 'blanks'

You'll need to specify setting name1 = null if that is what you want as well.

Hope this helps,

Alex

[small]----signature below----[/small]
Majority rule don't work in mental institutions

My Crummy Web Page
 
Please make sure you have a backup before trying that too.

[small]----signature below----[/small]
Majority rule don't work in mental institutions

My Crummy Web Page
 
To answer your question...Books On Line (BOL) can be your friend. This is from there for example:

Examples
A. Use one IF...ELSE block
This example shows an IF condition with a statement block. If the average price of the title is not less than $15, it prints the text: Average title price is more than $15.

USE pubs

IF (SELECT AVG(price) FROM titles WHERE type = 'mod_cook') < $15
BEGIN
PRINT 'The following titles are excellent mod_cook books:'
PRINT ' '
SELECT SUBSTRING(title, 1, 35) AS Title
FROM titles
WHERE type = 'mod_cook'
END
ELSE
PRINT 'Average title price is more than $15.'

Here is the result set:

The following titles are excellent mod_cook books:

Title
-----------------------------------
Silicon Valley Gastronomic Treats
The Gourmet Microwave

(2 row(s) affected)

B. Use more than one IF...ELSE block
This example uses two IF blocks. If the average price of the title is not less than $15, it prints the text: Average title price is more than $15. If the average price of modern cookbooks is more than $15, the statement that the modern cookbooks are expensive is printed.

USE pubs

IF (SELECT AVG(price) FROM titles WHERE type = 'mod_cook') < $15
BEGIN
PRINT 'The following titles are excellent mod_cook books:'
PRINT ' '
SELECT SUBSTRING(title, 1, 35) AS Title
FROM titles
WHERE type = 'mod_cook'
END
ELSE
IF (SELECT AVG(price) FROM titles WHERE type = 'mod_cook') > $15
BEGIN
PRINT 'The following titles are expensive mod_cook books:'
PRINT ' '
SELECT SUBSTRING(title, 1, 35) AS Title
FROM titles
WHERE type = 'mod_cook'
END

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top