[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 274
  • Last Modified:

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
1 Solution
Rajkumar GsSoftware EngineerCommented:
UPDATE YourTableName
SET field1 = '0' + field1
WHERE SUBSTRING(field1, 2, 1) = '-'
	AND DO = 'TEST' AND Revision = 'BASELINE'

Open in new window

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.

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now