復制代碼 代碼如下:
USE Demo
GO
/*
將表Code的列String中的值提取放到Record表中
String 中字符類型為
dsddddd,2222222,222221,3
其中最后一位為標記對于Record表中的BiaoJi
前面的以','分割的是值對應Record表中Value
*/
GO
DROP PROC proc_split_Code
GO
CREATE PROC proc_split_Code
AS
BEGIN
SET NOCOUNT ON
DECLARE @Count INT --條數(shù)
DECLARE @Index INT --變量
SET @Index = 1 --默認
SELECT @Count = Count(*) FROM Code
--PRINT @Count
WHILE (@Index=@Count)
BEGIN
DECLARE @BiaoJi INT -- 標記
DECLARE @String NVARCHAR(1000)--字符串
DECLARE @Temp INT --分隔符的位置
DECLARE @Star INT --開始位置
DECLARE @Code NVARCHAR(100) --
SET @Star = 0
SELECT @String=REVERSE(String)
FROM (
SELECT row_number() OVER(ORDER BY String) AS rownumber,* FROM Code
) AS a
WHERE rownumber between @Index and @Index
SET @Temp=CHARINDEX(',',@String,@Star)
SET @BiaoJi = SUBSTRING(@String,@Star,@Temp)
PRINT @BiaoJi
SET @String = REVERSE(@String)
SET @Temp=CHARINDEX(',',@String,@Star)
SET @Star = 0
WHILE(@Temp>0)
BEGIN
SET @Temp=CHARINDEX(',',@String,@Star)
--PRINT @Star
--PRINT @Temp
IF @Temp >0
BEGIN
SET @Code=SUBSTRING(@String,@Star,@Temp-@Star)
PRINT @Code
--插入到相應的表中
INSERT INTO Record(BiaoJi,Value,Time)
VALUES (@BiaoJi,@Code,getdate())
END
SET @Star=@Temp+1
END
--PRINT @Index
PRINT @String
SET @Index = @Index+1
END
END
GO
EXEC proc_split_Code