zintech
asked on
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
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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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 =
CASE
WHEN SUBSTRING(field1, 2, 1) = '-' THEN field1 = '0' + field1
ELSE field1
END
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
WHERE DO = 'TEST'
AND Revision = 'BASELINE'
AND SUBSTRING(field1, 2, 1) = '-'
This approach will perform better because only the records that must be changed are updated.
Approach #1:
UPDATE <table name>
SET field1 =
CASE
WHEN SUBSTRING(field1, 2, 1) = '-' THEN field1 = '0' + field1
ELSE field1
END
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
WHERE DO = 'TEST'
AND Revision = 'BASELINE'
AND SUBSTRING(field1, 2, 1) = '-'
This approach will perform better because only the records that must be changed are updated.
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