如何遍历sql server中的每一行?

时间:2012-10-23 06:41:27

标签: sql sql-server sql-server-2008 tsql

我的查询返回26个表名。

select name from sys.tables where name like '%JPro_VP_Service%'

现在我正在尝试编写一个查询来检查上面查询返回的每个表。

--consider this is my first table 
select * from JPro_VP_Service 
where row_id like '%1-101%' or row_id like '%1-102%'
-- likewise I want to search in 26 tables return from above query    

我想我需要写或光标来完成这个。

任何人都可以帮我解决这个问题吗?

4 个答案:

答案 0 :(得分:1)

最简单的方法是 试试这个:

SELECT 'select * from ' + name 
       + ' where row_id         like ''%1-101%'' or row_id like ''%1-102%''' 
FROM   sys.tables 
WHERE  name LIKE '%JPro_VP_Service%' 

您将获得具有相同条件的所有表格。你可以一起执行它们。

答案 1 :(得分:0)

答案 2 :(得分:0)

DECLARE @mn INT 
DECLARE @mx INT 
DECLARE @tblname VARCHAR(100); 

WITH cte 
     AS (SELECT Row_number() 
                  OVER ( 
                    ORDER BY (SELECT 0)) AS rn, 
                name 
         FROM   sys.tables 
         WHERE  name LIKE '%JPro_VP_Service%') 
SELECT @mn = Min(rn), 
       @mx = Max(rn) 
FROM   cte 

WHILE( @mn >= @mx ) 
  BEGIN 
      SELECT @tblname = name 
      FROM   cte 
      WHERE  rn = @mn 

      SELECT * 
      FROM   @tblname 
      WHERE  row_id LIKE '%1-101%' 
              OR row_id LIKE '%1-102%' 

      --Do something else 
      SET @mn=@mn + 1 
  END 

答案 3 :(得分:0)

此路线可能有效,但您可能希望将结果保存到表格中:

DECLARE @tables TABLE(
ID INT IDENTITY(1,1),
Name VARCHAR(100)
)

INSERT INTO @tables (Name)
SELECT name 
FROM sys.tables 
WHERE name like '%JPro_VP_Service%'

DECLARE @b INT = 1, @m INT, @table VARCHAR(100), @cmd NVARCHAR(MAX)
SELECT @m = MAX(ID) FROM @tables

WHILE @b <= @m
BEGIN

SELECT @table = Name FROM @tables WHERE ID = @b

SET @cmd = 'select * from ' + @table + '
where row_id like ''%1-101%'' or row_id like ''%1-102%''
'

EXECUTE sp_executesql @cmd

SET @b = @b + 1
SET @cmd = ''

END