2

我的查询返回 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    

我想我需要写 for 或 cursor 来完成这个。

谁能帮助我如何实现这一目标?

4

4 回答 4

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%' 

您将在相同条件下将所有表格放在一起。你可以一起执行它们。

于 2012-10-23T06:46:08.590 回答
0

是的,您必须为此使用游标,并且可能还需要动态 sql

另见

在 SQL Server 中生成动态 SQL 语句

动态 SQL 的优点和缺点

于 2012-10-23T06:44:06.137 回答
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 
于 2012-10-23T06:46:23.907 回答
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
于 2013-12-16T14:51:35.497 回答