我想在SQL Server中查询以下内容:
Select...FROM Database.dbo.[Table 1], [Table 2], [Table 3]
等等。
我没有为每个表编写唯一的select查询,而是编写一个,如下所示:
FROM Database.dbo.[All Tables]
最有效的方法是什么?我想我需要以某种方式定义所有表并将它们指向我想要查询的表的静态列表。
谢谢
答案 0 :(得分:0)
以下是您可能想要做的事情的几个例子。
1)SIMPLEST:要列出所有表,该命令将生成一个SQL命令列表,您可以将其粘贴到查询窗口并执行:
SELECT 'SELECT * FROM ' + TABLE_NAME + '; '
FROM INFORMATION_SCHEMA.TABLES
2)将TABLE_NAME添加到每个列表中,并仅显示每个列表的前3行。此外,虽然我通常只是复制/粘贴它们,但您可以尝试捕获变量中的所有内容,然后使用EXECUTE
执行变量内容:
DECLARE @SQL_CMDS NVARCHAR(MAX)
SET @SQL_CMDS = ''
SELECT @SQL_CMDS = @SQL_CMDS + CONVERT(VARCHAR(1000),
'SELECT TOP 3 [' + TABLE_NAME + '] = ''' + TABLE_NAME
+ ''' ,* FROM ' + TABLE_NAME + '; ')
FROM INFORMATION_SCHEMA.TABLES;
EXECUTE sp_executesql @SQL_CMDS
3)为可能包含订单号列的所有列添加WHERE
子句(如果您不确定它是ORDERNO
还是OrderNumber
还是Order_Num
):
DECLARE @SQL_CMDS NVARCHAR(MAX)
SET @SQL_CMDS = ''
SELECT @SQL_CMDS = @SQL_CMDS + CONVERT(VARCHAR(1000),
'SELECT [' + TABLE_NAME + '] = ''' + TABLE_NAME + ''' ,* FROM [' + TABLE_NAME
+ '] WHERE [' + COLUMN_NAME + '] = ''thisValueIWant'';')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE UPPER(COLUMN_NAME) LIKE '%ORDER%N%'
GROUP BY TABLE_NAME, COLUMN_NAME
ORDER BY TABLE_NAME, COLUMN_NAME;
EXECUTE sp_executesql @SQL_CMDS
希望有帮助...
答案 1 :(得分:0)
而不是:
Select...FROM Database.dbo.[Table 1], [Table 2], [Table 3]
每个表中必须至少有相同类型的列...然后你可以这样做:
SELECT id(or whatever column you have in common) FROM table1
union
SELECT id(or whatever column you have in common) FROM table2
union
SELECT id(or whatever column you have in common) FROM table3
等