简体   繁体   English

查询以从SQL Server中的字符串返回子字符串

[英]Query to return substring from string in SQL Server

I have a user defined function called Sync_CheckData under Scalar-valued functions in Microsoft SQL Server. 我在Microsoft SQL Server中的标量值函数下有一个名为Sync_CheckData的用户定义函数。 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) . 如果出现问题,则返回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 ). 从上面的字符串中,我想得到4,以便以后可以使用WHERE子句( WHERE Product_ID = 4 )选择出现错误的行。

Which SQL function can I use to get the substring ? 我可以使用哪个SQL函数获取substring

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)

I'd use RIGHT for this: 我会为此使用RIGHT

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) 小提琴示例: http ://sqlfiddle.com/#!3/d41d8/ 16397 (从上方更改)

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM