SQL Substring function with IF statement

I have the following statement that is throwing an error:

IF SUBSTRING(field1, 2, 1) = '-' THEN field1 = '0' + field1 END IF
WHERE     DO = 'TEST' AND Revision = 'BASELINE'

What I am trying to accomplish is to check if the second character in the field 'field1' is a hyphen '-' then if it is I would like to add a '0' to the beginning of field1
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Rajkumar GsSoftware EngineerCommented:
UPDATE YourTableName
SET field1 = '0' + field1
WHERE SUBSTRING(field1, 2, 1) = '-'
	AND DO = 'TEST' AND Revision = 'BASELINE'

Open in new window


Experts Exchange Solution brought to you by ConnectWise

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
John EastonDirectorCommented:
For MS SQL you should use the CASE statement.  For your code it would be something like:

SELECT myfield = CASE SUBSTRING(field1, 2, 1) WHERE '-' THEN '0' & field1 ELSE field1 END

I haven't used CASE must, so someone else may be able to post more accurate code.  For reference you can look at MSDN: http://msdn.microsoft.com/en-us/library/ms181765.aspx
For MS SQL Server, if you are trying to update a column in a table, then here us the syntax for two appoaches:

Approach #1:
UPDATE <table name>
SET field1 =
        WHEN SUBSTRING(field1, 2, 1) = '-' THEN field1 = '0' + field1
        ELSE field1
WHERE     DO = 'TEST' AND Revision = 'BASELINE'

I included this approach to illustrate how to use the CASE construct, but it has the disadvantage of causing every record in the table to be updated, regardless of whether SUBSTRING(field1, 2, 1) = '-'.

Approach #2:
UPDATE <table name>
SET field1 = '0' + field1
AND          Revision = 'BASELINE'
AND          SUBSTRING(field1, 2, 1) = '-'

This approach will perform better because only the records that must be changed are updated.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.