我需要将字符串数据转换为列:
DECLARE @STR varchar(max)
set @str = 'username=tiger,password=1234$'
I need result like the below in a temp table:
Field Value //Column names
userName tiger //values from the string
pasword 1234$ //values from the string
答案 0 :(得分:0)
这里的许多假设,例如格式总是相同等,但它会让你开始。
DECLARE @STR varchar(max)
SET @str = 'username=tiger,password=1234$'
SELECT
'username' AS Field
, SUBSTRING(@str, 10, CHARINDEX(',', @str) - 10) AS Value
UNION ALL
SELECT
'password'
, SUBSTRING(@str, PATINDEX('%password=%', @str) + 9, LEN(@str) - PATINDEX('password=%', @str))
答案 1 :(得分:0)
Here ,we go:
DECLARE @Str VARCHAR(MAX)
set @str = 'username=vmunshi,paswword=1234$'
DECLARE @TempMain TABLE (FieldName Varchar(Max), Value VARCHAR(MAX))
DECLARE @TempTBL TABLE (Items Varchar(Max))
INSERT INTO @TempTBL SELECT Item FROM dbo.fn_SplitString(@Str, ',');
WITH CTE AS
(
SELECT T.Items,
LEN(T.Items)-LEN(REPLACE(Items,'=','')) N
FROM @TempTBL T
)
INSERT INTO @TempMain
SELECT
PARSENAME(REPLACE(Items,'=','.'),N+1) AS FieldName,
PARSENAME(REPLACE(Items,'=','.'),N) AS Value
FROM CTE
select * from @TempMain
功能:
CREATE FUNCTION [dbo].[fn_SplitString]
(
@Input NVARCHAR(MAX),
@Character CHAR(1)
)
RETURNS @Output TABLE (
Item NVARCHAR(1000)
)
AS
BEGIN
DECLARE @StartIndex INT, @EndIndex INT
SET @StartIndex = 1
IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
BEGIN
SET @Input = @Input + @Character
END
WHILE CHARINDEX(@Character, @Input) > 0
BEGIN
SET @EndIndex = CHARINDEX(@Character, @Input)
INSERT INTO @Output(Item)
SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)
SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
END
RETURN
END