我有一个名为StateNames From Customer Table的SQL数据库列
StateCode COLUMN具有数据类似
27 MAHARASHTRA
23 BIHAR
234 SHILONG
等。
我必须只选择字符串Part .. I.e MAHARASHTRA
或BIHAR
..
请建议
答案 0 :(得分:0)
CREATE FUNCTION [dbo].[Split] (@sep char(1), @s varchar(5120))
RETURNS table
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(@sep, @s)
UNION ALL
SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
FROM Pieces
WHERE stop > 0
)
SELECT pn AS [Index],
SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 5120 END) AS [Value]
FROM Pieces
)
然后
SELECT [Value] FROM dbo.Split(' ', YourColumnName) WHERE [Index] = 2
答案 1 :(得分:0)
如果分隔符是特定字符,如空格,则使用CHARINDEX
。
DECLARE @StateCode VARCHAR(100) = '234 SHILONG'
SELECT
Original = @StateCode,
PositionOfSpace = CHARINDEX(' ', @StateCode),
State = CASE
WHEN CHARINDEX(' ', @StateCode) > 0
THEN SUBSTRING(
@StateCode,
CHARINDEX(' ', @StateCode) + 1,
100)
ELSE
@StateCode END