我有那個查詢
USE database_A /*it will change: database_B, c , d etc..*/
select X.Name1, X.Name2, DB_NAME() AS [Current Database]
from dbo.table1 A /*it will be the same table*/
left join
database_X.dbo.table_X X /*it will be the same database and table*/ on A.ID = X.ID_ID
我想得到一個結果,顯示 Name1 和 Name2 的值以及創建它的背景關系,例如:
| 姓名1 | 姓名2 | 當前資料庫 |
|---|---|---|
| 一 | 二 | 資料庫_A |
| 啊啊啊 | 滴滴 | 資料庫_A |
| 一 | 二 | 資料庫_B |
| 一 | 二 | 資料庫_B |
| 222 | 1112 | 資料庫_B |
| 一 | 二 | 資料庫_c |
uj5u.com熱心網友回復:
動態sql示例
-- list of DBs
create table dbs (dbn sysname);
insert dbs
values ('dbnameA'),('dbnameB'),('dbnameC');
-- build the query
declare @q varchar(Max);
select @q = string_agg(s, ' union all ')
from (
select 'select X.Name1, X.Name2, ''' dbn ''' AS [Current Database]'
' from ' dbn '.dbo.table1 A'
' left join database_X.dbo.table_X X on A.ID = X.ID_ID' s
from dbs) t
-- check it
select @q;
-- run it
exec (@q);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/367512.html
標籤:sql
上一篇:根據其他3列的值創建一列
