我有两个变量,例如:
@FieldName
@values
这两个变量的值如下:
@FieldName
- 包含[a],[b],[c],[d]
@values
- 包含5,6,7,8
现在我只需要检索'b'
&列的数据'd'
。
我们怎样才能得到b=6 & d=8
?
提前致谢。
我有两个变量,例如:
@FieldName
@values
这两个变量的值如下:
@FieldName
- 包含[a],[b],[c],[d]
@values
- 包含5,6,7,8
现在我只需要检索'b'
&列的数据'd'
。
我们怎样才能得到b=6 & d=8
?
提前致谢。
好吧,我讨厌在 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,而不是在不同的列表中
试试这个:
使用 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