我发送一个由一系列Tax-Value
对组成的串联字符串到数据库中进行拆分,然后插入到表的两列中。我已经有一个使用光标的方法,但我想知道在这种情况下是否有更好的光标替换?
我的字符串如下所示:VAT|10#CST|20#ST|30#VAT|40#WCT|50#OCT|60#FP|70#CD|80#OT|90#
税金和价值以|
分隔,行以#
我使用函数来分割这个字符串: 例如: -
select * from isplit('VAT|10#CST|20#ST|30#VAT|40#WCT|50#OCT|60#FP|70#CD|80#OT|90#','#')
返回9行第一个单元格由identity srno
组成,第二个单元格由tax|value
Create FUNCTION [dbo].[ISplit](@String nvarchar(4000), @Delimiter char(1))
RETURNS @Results TABLE (SrNo int identity, Items nvarchar(4000))
AS
BEGIN
DECLARE @INDEX INT
DECLARE @SLICE nvarchar(4000)
SELECT @INDEX = 1
IF @String IS NULL RETURN
WHILE @INDEX !=0
BEGIN
SELECT @INDEX = CHARINDEX(@Delimiter,@STRING)
IF @INDEX !=0
SELECT @SLICE = LEFT(@STRING,@INDEX - 1)
ELSE
SELECT @SLICE = @STRING
INSERT INTO @Results(Items) VALUES(@SLICE)
SELECT @STRING = RIGHT(@STRING,LEN(@STRING) - @INDEX)
IF LEN(@STRING) = 0 BREAK
END
RETURN
END
我计划将连接的字符串拆分为#temp表,然后再使用游标将其拆分并存储在#temp1表中,然后使用此#temp1插入两个列值,即。税收和价值。 insert into sometable (tax,value) values(@tax,@value)
select * into #temp from split('VAT|10#CST|20#ST|30#VAT|40#WCT|50#OCT|60#FP|70#CD|80#OT|90#','#')
DECLARE @row varchar(20)
DECLARE @Temp CURSOR
SET @Temp = CURSOR FOR
SELECT *
FROM #temp
OPEN @Temp
FETCH NEXT
FROM @Temp INTO @row
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @row
select * into #temp1 from iSplit(@row,'|')
declare @tax varchar(10)
declare @value varchar(10)
select @tax= items from #temp1 where srno=1
select @value= items from #temp1 where srno=2
insert into sometable (tax,value) values(@tax,@value)
FETCH NEXT
FROM @Temp INTO @row
END
CLOSE @Temp
DEALLOCATE @Temp
在这种情况下,是否有游标或for语句的替代方法?
答案 0 :(得分:0)
这需要吗?
不改变功能:
INSERT INTO sometable
(tax,
value)
SELECT Substring(items, 0, Charindex('|', items, 0)) AS tax,
Substring(items, Charindex('|', items, 0) + 1, Len(items)) AS value
FROM [Isplit]('VAT|10#CST|20#ST|30#VAT|40#WCT|50#OCT|60#FP|70#CD|80#OT|90#', '#')
更改功能:
ALTER FUNCTION [dbo].[ISplit](@String nvarchar(4000), @Delimiter char(1))
RETURNS @Results TABLE (SrNo int identity, tax nvarchar(4000),value numeric(22,6))
AS
BEGIN
DECLARE @INDEX INT
DECLARE @SLICE nvarchar(4000)
SELECT @INDEX = 1
IF @String IS NULL RETURN
WHILE @INDEX !=0
BEGIN
SELECT @INDEX = CHARINDEX(@Delimiter,@STRING)
IF @INDEX !=0
SELECT @SLICE = LEFT(@STRING,@INDEX - 1)
ELSE
SELECT @SLICE = @STRING
INSERT INTO @Results(tax,value)
select Substring(@SLICE, 0, Charindex('|', @SLICE, 0)),
Substring(@SLICE, Charindex('|', @SLICE, 0) + 1, Len(@SLICE)) AS value
SELECT @STRING = RIGHT(@STRING,LEN(@STRING) - @INDEX)
IF LEN(@STRING) = 0 BREAK
END
RETURN
END
INSERT INTO sometable
(tax,
value)
SELECT tax,value from Isplit('VAT|10#CST|20#ST|30#VAT|40#WCT|50#OCT|60#FP|70#CD|80#OT|90#', '#')