我想列出所有指定的表及其包含在SQL Server中的ID。
例如:
客户表
| id | foo |
|:---|:----:|
| 1 | This |
| 2 | Col |
用户表
| id | bar |
|:---|:----:|
| 1 | That |
| 2 | Col |
| 3 | Col |
| 4 | Col |
我想生成这样的结果:
| TableName | ID |
|:---------:|:----:|
| Client | 1 |
| Client | 2 |
| User | 1 |
| User | 2 |
| User | 3 |
| User | 4 |
我要做的是列出所有所需的表名,但是我不知道如何列出其IDs
SELECT t.name AS TableName
FROM sys.tables as t
WHERE t.name = 'Client'
OR t.name = 'User'
输出:
| - | TableName |
|---| --------- |
| 1 | Client |
| 2 | User |
有什么想法吗?
答案 0 :(得分:4)
您需要UNION ALL
:
SELECT 'Client' AS TableName, ID
FROM Client
UNION ALL
SELECT 'User', ID
FROM User;
答案 1 :(得分:0)
您需要UNION
SELECT T.Name,
C.ID
FROM Sys.Tables T CROSS APPLY
Clients C
WHERE T.Name = 'Clients'
UNION
SELECT T.Name,
U.ID
FROM Sys.Tables T CROSS APPLY
Users U
WHERE T.Name = 'Users'