0
我有一個員工姓名列表和一個表列表。我需要迭代所有員工姓名並查找哪個表的員工姓名存在。所有要迭代的表存在於同一臺服務器和同一個數據庫中。列出所有包含特定員工姓名的表
樣本數據結構
Create Table TableNamesToCheck (dbName varchar(15))
Insert Into TableNamesToCheck
Values ('table1'), ('table2'), ('table3'), ('table4'), ('table5'),
('table6'), ('table7'), ('table8'), ('table9'), ('table10')
Create Table EN (employeename varchar(100))
Insert Into EN
Values ('Richard Marx'), ('Joseph Jones'), ('Mark Badcock'),
('Frank Fins'), ('Richard James'), ('Fall Fren'), ('Hiu Hen')
謝謝@Giorgi ---我明白使用光標對我表名,但我如何加入兩個表,當他們沒有類似的領域上加入2個表?這是我的(工作正在進行),如果我明白你在解釋這是我的語法,但它給了我每個員工和每個表的以下錯誤...
Msg 207,Level 16,狀態1,行1 無效的列名稱'employeename'。 消息207,級別16,狀態1,行1 列名稱'Richard'無效。
Declare @dbname varchar(25), @empname varchar(100), @sql varchar(Max)
Create Table TableNamesToCheck (dbName varchar(15))
Insert Into TableNamesToCheck
Values ('table1'), ('table2'), ('table3'), ('table4'), ('table5'),
('table6'), ('table7'), ('table8'), ('table9'), ('table10')
Create Table EN (employeename varchar(100))
Insert Into EN
Values ('Richard Marx'), ('Joseph Jones'), ('Mark Badcock'),
('Frank Fins'), ('Richard James'), ('Fall Fren'), ('Hiu Hen')
Declare c1 Cursor For
Select dbname
From TableNamesToCheck
Open c1
Fetch Next from c1 into @dbname
Declare c2 Cursor For
Select employeename
From EN
Open c2
Fetch Next from c2 into @empname
While @@FETCH_STATUS = 0
Begin
While @@FETCH_STATUS = 0
Begin
Set @sql = 'Select '[email protected]+' From TableNamesToCheck where employeename IN (Select '[email protected]+' from EN)'
Exec (@sql)
Fetch Next From c1 Into @dbname
Fetch Next From c2 Into @empname
End
End
Close c1
Close c2
Deallocate c1
Deallocate c2
Drop Table TableNamesToCheck
Drop Table EN
您需要光標在表名的表,和左連接連接表的表,從表名。所有這些都在使用exec函數的動態查詢中。 –