SQL Query非命名完整的数据库名称

时间:2016-10-14 05:25:39

标签: sql sql-server tsql

我有一组完全相同但只更改第一个值的表,它的日期值如下:

dbo.[2016_09_06_CHEQ]

所以不是编写相同的查询,而是更改名称中的日期,有没有办法搜索所有表?这样的事情?

dbo.[*_CHEQUES]??

有没有办法做到这一点?或者如何在我的陈述中存档这样的东西

3 个答案:

答案 0 :(得分:1)

另一种选择是使用游标:

DECLARE @tableName VARCHAR(50)
DECLARE @query NVARCHAR(MAX) = ''

DECLARE db_cursor CURSOR FOR  

    SELECT TABLE_NAME
    FROM INFORMATION_SCHEMA.Tables
    WHERE TABLE_TYPE = 'BASE TABLE'
    AND TABLE_NAME LIKE '%_CHEQUES'

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @tableName  

WHILE @@FETCH_STATUS = 0  
BEGIN  
    SET @query = @query + 'SELECT CommonField1, CommonField2 FROM ' + @tableName + ' WHERE CommonField3 = value '

    FETCH NEXT FROM db_cursor INTO @tableName  
    IF @@FETCH_STATUS = 0
--      SET @query = @query + CHAR(13) + CHAR(10) + 'UNION ALL ' + CHAR(13) + CHAR(10) -- To add line breaks for easier reading when debugging
        SET @query = @query + 'UNION ALL '
END  

CLOSE db_cursor
DEALLOCATE db_cursor

--PRINT @query -- To debug the result query
EXEC sp_executesql @query

答案 1 :(得分:0)

可能是这样的:

declare @q nvarchar(MAX) = 'SELECT * FROM '

;with cte as (
SELECT TABLE_NAME 
FROM information_schema.tables 
WHERE TABLE_TYPE='BASE TABLE'
AND table_name like '%_CHEQ'
)
select @q = @q + '[' + table_name + '] UNION SELECT * FROM ' FROM cte

SET @q = SUBSTRING(@q, 1, LEN(@q) - 19)
EXEC sp_executesql @q

答案 2 :(得分:0)

我假设您使用的是SQL Server。 您可以将未记录的过程sp_MSforeachtable与此sys存储过程一起使用,您可以使用单个语句从表中检索所有信息

USE YOUR_DATABASE GO EXEC master.sys.sp_MSforeachtable @command1="SELECT * FROM ?"

此语句在数据库中存在的每个表中运行SELECT。 您也可以使用动态查询

    DECLARE @name varchar(400),
@sql varchar(4000)

SELECT @name = (SELECT TOP 1(name) FROM sys.objects WHERE type = 'U' and name like '%CHEQ%' ORDER BY name)
WHILE @name IS NOT NULL
BEGIN
    SELECT @sql = 'SELECT * FROM [dbo].['+@name+']'
    EXEC(@sql)
    PRINT 'TABLE PROCESSED: '+@name
    SELECT @name = (SELECT TOP 1(name) FROM sys.objects WHERE type = 'U' AND name > @name ORDER BY name)
END
GO