1

I have a user defined function called Sync_CheckData under Scalar-valued functions in Microsoft SQL Server. What it actually does is to check the quantity of issued product and balance quantity are the same. If something is wrong, returns an ErrorStr nvarchar(255).

Output Example:

Balance Stock Error for Product ID : 4

From the above string, I want to get 4 so that later on I can SELECT the rows which is giving errors by using WHERE clause (WHERE Product_ID = 4).

Which SQL function can I use to get the substring?

1
  • Is it always the last digit before the semi colon? Commented Jun 28, 2013 at 2:59

3 Answers 3

3

Try this

DECLARE @STR AS VARCHAR(1000)
SELECT @STR='Balance Stock Error for Product ID : 4'

SELECT substring(@STR,charINDEX(':',@STR)+1,LEN(@STR)-charINDEX(':',@STR)+1)
Sign up to request clarification or add additional context in comments.

2 Comments

+1 -- no need for the added charindex at the end -- it will truncate accordingly. Here's a Fiddle Demo: sqlfiddle.com/#!3/d41d8/16396
Thank you so much, tsohtan! I got it.
1

I'd use RIGHT for this:

declare @response varchar(100)
set @response = 'Balance Stock Error for Product ID : 4'

select right(@response, len(@response) - charindex(':', @response))

Sample fiddle: http://sqlfiddle.com/#!3/d41d8/16397 (altered from above)

Comments

1

Try this

DECLARE @String VARCHAR(100)

SET @String = 'Balance Stock Error for Product ID : 4'

SELECT RIGHT(@string, CHARINDEX(':', REVERSE(@string))-2)

OR

SELECT RIGHT(@string,(LEN(@string)+1)-PATINDEX('%[0-9]%', @string))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.