我有一个主表和两个明细表,每个明细表都与该主表相关。
为简单起见,[dbo].[tb_Master]
有一个称为[Id]
的唯一密钥。
称为[dbo]。[tb_DetailA]和[dbo]。[tb_DetailB]的两个详细信息表中的每一个都有对[dbo]的引用(不是实际的外键,这些表仅在逻辑上连接)。[tb_Master]由他们的[IdMaster]字段调解。
因此,简而言之,架构类似于以下内容:
[dbo].[tb_Master]
(
[Id] (K)
[MasterDescription]
)
[dbo].[tb_DetailA]
(
[Id] (K)
[IdMaster] --logical FK to tb_Master
[UniqueValue] --value subject to unique constraint and known to be bound to certain domain D1 (range of values) even if that bound is no enforced in any way different than the unique constraint
[DetailADescription]
)
[dbo].[tb_DetailB]
(
[Id] (K)
[IdMaster] --logical FK to tb_Master
[UniqueValue] --value subject to unique constraint and known to be bound to certain domain D1 (range of values) even if that bound is no enforced in any way different than the unique constraint. (same domain D1 of tb_DetailA)
[DetailBDescription]
)
我要弄清楚的是,这是检索特定主数据库(又名[IdMaster])和特定元素(跨所有这三个表)的最佳方法(即最佳实践)。域D1。
我尤其不清楚这两者之间最好的选择:
DECLARE @myMasterId AS INT = KNOWN_MESTER_ID_OF_INTEREST --may be that not exist anymore
DECLARE @myUniqueDomainElement AS ..SOMETHING.. = KNOWN_VALUE; --may be that not exist anymore
DECLARE @fewVariableHereToStoreResult..
SELECT TOP(1)
@fewVariableHereToStoreResult_1 = [MasterDescription] ,
@fewVariableHereToStoreResult_2 = [DetailADescription],
@fewVariableHereToStoreResult_3 = [DetailBDescription]
FROM [tb_Master]
INNER JOIN [tb_DetailA] ON [tb_Master].[Id] = [tb_DetailA].[IdMaster]
INNER JOIN [tb_DetailB] ON [tb_Master].[Id] = [tb_DetailB].[IdMaster]
WHERE [tb_DetailA].[UniqueValue] = @myUniqueDomainElement AND
[tb_DetailB].[UniqueValue] = @myUniqueDomainElement
IF ( @@ROWCOUNT < 1 )
BEGIN
--handle the exception, I'm in a stored procedure, the exception can not specify which 'entity' is not found among the three tables
END
相对于此方法:
DECLARE @myMasterId AS INT = KNOWN_MESTER_ID_OF_INTEREST --may be that not exist anymore
DECLARE @myUniqueDomainElement AS ..SOMETHING.. = KNOWN_VALUE; --may be that not exist anymore
DECLARE @fewVariableHereToStoreResult..
SELECT TOP(1) @fewVariableHereToStoreResult_1 = [MasterDescription] FROM [tb_Master] WHERE [Id] = @myMasterId
IF ( @@ROWCOUNT < 1 )
BEGIN
--handle the exception, I'm in a stored procedure, the exception now can specify which tables (aka 'entity') raise the problem.
END
SELECT TOP(1) @fewVariableHereToStoreResult_2 = [DetailADescription] FROM [tb_DetailA] WHERE [IdMaster] = @myMasterId AND [UniqueValue] = myUniqueDomainElement
IF ( @@ROWCOUNT < 1 )
BEGIN
--handle the exception, I'm in a stored procedure, the exception now can specify which tables (aka 'entity') raise the problem.
END
SELECT TOP(1) @fewVariableHereToStoreResult_3 = [DetailBDescription] FROM [tb_DetailB] WHERE [IdMaster] = @myMasterId AND [UniqueValue] = myUniqueDomainElement
IF ( @@ROWCOUNT < 1 )
BEGIN
--handle the exception, I'm in a stored procedure, the exception now can specify which tables (aka 'entity') raise the problem.
END