在SQL中将动态选择值传递给游标(游标用法)

时间:2016-10-19 15:05:46

标签: sql sql-server database sql-server-2008

我是游标新手,

我应该如何在游标中编写以下代码以将列值传递给变量@str

基本上@str在下面的代码中取静态值,需要传递表列值

DECLARE @str VARCHAR(1000), 
          @str1 VARCHAR(1000), 
          @str2 VARCHAR(1000), 
          @pos INT, 
          @counter INT 

SET @str = '45 | 00055 | 9/30/2016 | Vodafone | Randy Singh | Newyork | Test Msg | TBL101 | PC | 1.00 | COMP101 | CS | 1.00.............. etc'

(Here i need to pass table column value like--- select name from Order so every time it takes new value)

--select @str = temp FROM OrderTemp

SET @counter = 0 
SET @pos = 0 

WHILE @counter <= 6
BEGIN   
SET @pos = CHARINDEX('|', @str, @pos + 1)   
SET @counter = @counter + 1 
END 

SET @str1 = SUBSTRING(@str, 1, @pos) 
SET @str2 = SUBSTRING(@str, @pos+1, LEN(@str)-@pos) 

insert into OrderInterface (name)(SELECT @str2)
insert into OrderInterface (Id)(SELECT @str1)

输入

@str :-- '45 | 00055 | 9/30/2016 | Vodafone | Randy Singh | Newyork | Test Msg | TBL101 | PC | 1.00 | COMP101 | CS | 1.00.............. etc'

Now i need to pass Input value from table like : Select name from tablename instead of static values. 

输出

@str1 :-- '45 | 00055 | 9/30/2016 | Vodafone | Randy Singh | Newyork | Test Msg'

@str2 :-- 'TBL101 | PC | 1.00 | COMP101 | CS | 1.00.............. etc'

2 个答案:

答案 0 :(得分:1)

好的,假设#Temp看起来像这样:

enter image description here

然后我们可以执行以下操作:

;with cte as (
              Select A.RN,B.* 
               From  (Select *,RN = Row_Number() over(Order By (Select NULL)) From #Temp) A
               Cross Apply [dbo].[udf-Str-Parse](A.Temp,' | ') B
             )
-- Insert Into OrderInterface  (Name,ID)
Select Name = (Select String1=Stuff((Select  ' | ' + RetVal From cte Where RN=A.RN and RetSeq<=7 For XML Path ('')),1,3,'') )
      ,ID =   (Select String1=Stuff((Select  ' | ' + RetVal From cte Where RN=A.RN and RetSeq>7  For XML Path ('')),1,3,'') )
 From cte A
 Group By A.RN

返回

enter image description here

需要的UDF

CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table 
As
Return (  
    Select RetSeq = Row_Number() over (Order By (Select null))
          ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
    From (Select x = Cast('<x>'+ Replace(@String,@Delimiter,'</x><x>')+'</x>' as xml).query('.')) as A 
    Cross Apply x.nodes('x') AS B(i)
);
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')

答案 1 :(得分:0)

认为您要做的是找到由|取消的字符串中的第6个元素。

如果是这种情况你不应该在SQL Server中使用循环(在SQL中总是如此),你可以使用STRING_SPLIT函数(https://msdn.microsoft.com/en-us/library/mt684588.aspx),如下所示:

SELECT value  
FROM STRING_SPLIT(@sql, ' | ')  
OFFSET ROWS 5 FETCH FIRST 1 ROW ONLY