如何在存储过程中使用循环

时间:2015-03-19 11:35:23

标签: sql-server-2008 c#-4.0 stored-procedures datatable

我有一个数据表,它作为参数传递给StoredProcedure,我想在存储过程中为数据表中的每一行执行查询。

datatable:
Value     
000011%
000012%
000013%
000014%
000015%
000016%

Query goes like this:
SELECT * FROM Test T
         INNER JOIN Sample S ON T.TestId=S.SampleID
         WHERE Title like'000011%' //This value will change for each datatbale row value 

2 个答案:

答案 0 :(得分:0)

我认为你不需要循环。通过查看您的数据,您可以尝试LEFT()功能。

SELECT * 
FROM Test T
         INNER JOIN Sample S ON T.TestId = S.SampleID
WHERE LEFT(Title, 6) IN (SELECT LEFT(Value, 6) FROM ParaTable)

答案 1 :(得分:0)

尝试CROSS JOIN

DECLARE @DT TABLE(V NVARCHAR(MAX))
DECLARE @T TABLE(Title NVARCHAR(MAX))

INSERT INTO @DT VALUES
('000011%'),
('000012%'),
('000013%'),
('000014%'),
('000015%'),
('000016%')

INSERT INTO @T VALUES
('000011123'),
('00001112345'),
('000012123'),
('000012123678'),
('000013ABC'),
('DEF'),
('GHI')

SELECT * FROM @DT dt
CROSS JOIN @T t
WHERE t.Title LIKE dt.V

输出:

V       Title
000011% 000011123
000011% 00001112345
000012% 000012123
000012% 000012123678
000013% 000013ABC

应用于您的查询:

SELECT * FROM Test T
         INNER JOIN Sample S ON T.TestId=S.SampleID
         CROSS APPLY datatable dt
         WHERE Title like dt.Value