我正在设计一个简单的办公室门票系统,并希望为负责下一步行动的一方提供一个字段。为了做到这一点,我正在考虑使用tableName
和tableID
作为特定责任方的指定人员(可以是技术人员,客户或第三方,所有人都在不同的表格中)< / p>
将数据拉入并使用表的名称作为参数运行另一个select调用是可以的,但额外的数据流会显着减慢速度。
有没有办法使用单个join语句返回聚会的详细信息,其中包含表名的列和一个用于单个表id的列,或者是否有更好的方法来存储来自多个潜在表的数据? / p>
答案 0 :(得分:0)
您可以使用左连接来满足您的要求: -
Set Nocount On;
Declare @OfficeTickets Table
(
Id Int Identity(1,1)
,Column1 Varchar(100)
,PartyType Varchar(1)
,TechnicianId Int Null
,CustomerId Int Null
,ThirdPartyId Int Null
)
Declare @OfficeTickets1 Table
(
Id Int Identity(1,1)
,Column1 Varchar(100)
,TableName Varchar(100)
,TableId Int Null
)
Declare @Technician Table
(
Id Int Identity(1,1)
,TechnicianName Varchar(100)
)
Declare @Customers Table
(
Id Int Identity(1,1)
,CustomerName Varchar(100)
)
Declare @ThirdParty Table
(
Id Int Identity(1,1)
,ThirdPartyName Varchar(100)
)
Insert Into @Technician(TechnicianName) Values
('Technician_1')
,('Technician_2')
,('Technician_3')
Insert Into @Customers(CustomerName) Values
('Customer_1')
,('Customer_2')
,('Customer_3')
Insert Into @ThirdParty(ThirdPartyName) Values
('ThirdParty_1')
,('ThirdParty_2')
,('ThirdParty_3')
,('ThirdParty_4')
Insert Into @OfficeTickets(Column1,PartyType,TechnicianId,CustomerId,ThirdPartyId) Values
('ABC','T',3,Null,Null)
,('XYZ','C',Null,2,Null)
,('PUQ','P',Null,Null,4)
Insert Into @OfficeTickets1(Column1,TableName,TableId) Values
('ABC','Technician',3)
,('XYZ','Customers',2)
,('PUQ','ThirdParty',4)
---- taken separate columns for parties
Select ot.Id
,ot.Column1
,t.TechnicianName
,c.CustomerName
,tp.ThirdPartyName
From @OfficeTickets As ot
Left Join @Technician As t On ot.PartyType = 'T' And ot.TechnicianId = t.Id
Left Join @Customers As c On ot.PartyType = 'C' And ot.CustomerId = c.Id
Left Join @ThirdParty As tp On ot.PartyType = 'P' And ot.ThirdPartyId = tp.Id
---- by TableName and TableId
Select ot.Id
,ot.Column1
,t.TechnicianName
,c.CustomerName
,tp.ThirdPartyName
From @OfficeTickets1 As ot
Left Join @Technician As t On ot.TableName = 'Technician' And ot.TableId = t.Id
Left Join @Customers As c On ot.TableName = 'Customers' And ot.TableId = c.Id
Left Join @ThirdParty As tp On ot.TableName = 'ThirdParty' And ot.TableId = tp.Id
<强>输出: - 强>