在进行sql查询时,我有一个字段 Gift_Number ,它给我以下数据
Gift certificat (-) [2989153053216]
Sql Query:
SELECT SUBSTRING(H.F1056, patindex('%[^0]%',H.F1056), 10) AS Shop_Number
, '000' AS Cashier_Code
, H.F1057 AS Terminal_number
, REPLACE(CONVERT(VARCHAR(10), H.F254, 103), '/', '') AS Todays_Date
, STIME AS Ticket_Time
, H.F1032 AS Ticket_Number
, K.F1063 AS Mode_Of_Payment
, K.F02 AS Mode_Of_Payment_Desc
, CASE WHEN J.F1063 = 117
THEN J.F02
ELSE '' END AS Gift_Number
, CASE WHEN I.F02 = 'TOTAL'
THEN I.F65
ELSE 0 END AS Total_Ticket
FROM [READEJ_H] H
LEFT OUTER JOIN [dbo].[READEJ_I] I
ON (H.F1101 = I.F1101 AND I.F02 = 'TOTAL')
LEFT OUTER JOIN [dbo].[READEJ_I] K
ON (H.F1101=K.F1101 AND K.F1063 BETWEEN 100 AND 199)
LEFT OUTER JOIN [dbo].[READEJ_I] J
ON (H.F1101=J.F1101 AND J.F1063 = 117)
WHERE I.F65 <> CONVERT(DOUBLE PRECISION,0)
如何仅提取sql select语句中方括号之间的信息。输出应如下所示:
2989153053216
答案 0 :(得分:2)
可能最简单的方法是使用charindex
和substring
:
DECLARE @S varchar(100) = 'Gift certificat (-) [2989153053216]'
SELECT SUBSTRING(@S, CHARINDEX('[', @S)+1, CHARINDEX(']', @S) - CHARINDEX('[', @S)-1)
结果:2989153053216
但是,您应该知道,如果字符串不包含分隔符,或者]
分隔符位于[
分隔符之前,则会引发错误。