从单个SQL Server变量中检索多个数据

时间:2012-10-22 05:11:05

标签: sql sql-server stored-procedures

我有两个变量,如:

@FieldName 
@values

这两个变量的值如下:

  • @FieldName - 包含[a],[b],[c],[d]
  • @values - 包含5,6,7,8

现在我需要检索列'b'&的数据。仅'd'

我们如何获得b=6 & d=8

提前致谢。

2 个答案:

答案 0 :(得分:1)

我讨厌在SQL Server上做这样的事情,但是

declare @FieldName nvarchar(max) = '[a],[b],[c],[d]'
declare @values nvarchar(max) = '5,6,7,8'
declare @i int, @j int, @break int
declare @a nvarchar(max), @b nvarchar(max), @result nvarchar(max)

select @break = 0

while @break = 0
begin
    select @i = charindex(',', @FieldName), @j = charindex(',', @values)

    if @i > 0 and @j > 0
    begin
        select @a = left(@FieldName, @i - 1), @b = left(@values, @j - 1)

        select @FieldName = right(@FieldName, len(@FieldName) - @i), @values = right(@values, len(@values) - @j)
    end
    else
    begin
        select @a = @FieldName, @b = @values, @break = 1
    end

    if @a in ('[b]', '[d]')
        select @result = isnull(@result + ' & ', '') + @a + '=' + @b

select @result

您也可以将所有这些列表放入临时/变量表中并加入。

select *
from
(
    select T.<yourcolumn>, row_number() over (order by T.<yourcolumn>) as rownum
    from <temptable1> as T
) as F
    inner join
    (
        select T.<yourcolumn>, row_number() over (order by T.<yourcolumn>) as rownum
        from <temptable2> as T
    ) as V on V.rownum = F.rownum

或者,更好的是,您可以将参数传递给xml形式的sp而不是不同的列表

答案 1 :(得分:1)

试试这个:
使用XML我正在尝试将值溢出并将结果存储在表变量

    DECLARE @FieldName VARCHAR(MAX),
    @values varchar(max)

    SET @FieldName = 'a,b,c,d';
    SET @values = '5,6,7,8'

    SET @FieldName = @FieldName + ',';
    SET @values = @values + ',';

    DECLARE @X XML
    SET @X = CAST('<Item>' + REPLACE(@FieldName, ',', '</Item><Item>') + '</Item>' AS XML)

    Declare @X1 XML
    Set @X1=CAST('<Position>' + REPLACE(@values, ',', '</Position><Position>') + '</Position>' AS XML)

    Declare @FieldSample table
    (
     FieldName char(1),
     rowNum int
    )

    Declare @valueSample table
    (position int,
     rowNum int)

    Insert into @FieldSample(rowNum,FieldName)
    Select * from  (
    SELECT row_number() over (order by (select 0)) as rowNum, t.value('.', 'char(1)')   as field
    FROM @x.nodes('/Item') as x(t)
    ) as a
   where a.field !=''

   Insert into @valueSample(rowNum,position)
   Select * from (
   Select row_number() over (order by (select 0)) as rowNum, k.value('.', 'int') as position
   from @X1.nodes('/Position') as x1(k) 
   ) as b
   where b.position !=0

基本上你可以根据你打算获取数据的方式来改变它的最后一个逻辑

  Select a.FieldName,b.position from @FieldSample as a
  inner join @valueSample as b
  on a.rowNum=b.rowNum
  where b.position = 6 or b.position =8