我已经看到了几种用于“克服” SQL Server 中缺少常量的模式,但它们似乎都不能同时满足性能和可读性/可维护性的问题。
在下面的示例中,假设我们的表中有一个完整的“状态”分类,选项似乎是:
- 只是硬编码,可能只是“评论”状态
-- StatusId 87 = Loaded
SELECT ... FROM [Table] WHERE StatusId = 87;
- 使用状态查找表,然后加入该表,以便
WHERE
子句引用友好名称。
子查询:
SELECT ...
FROM [Table]
WHERE
StatusId = (SELECT StatusId FROM TableStatus WHERE StatusName = 'Loaded');
或加入
SELECT ...
FROM [Table] t INNER JOIN TableStatus ts On t.StatusId = ts.StatusId
WHERE ts.StatusName = 'Loaded';
- 定义了一堆标量 UDF,它们返回常量,即
CREATE Function LoadedStatus()
RETURNS INT
AS
BEGIN
RETURN 87
END;
进而
SELECT ... FROM [Table] WHERE StatusId = LoadedStatus();
(IMO 这会在数据库中造成大量污染——这在 Oracle 包包装器中可能没问题)
- And similar patterns with Table Valued Functions holding the constants with values as rows or columns, which are
CROSS APPLIED
back to[Table]
How have other SO users have solved this common issue?
Edit : Bounty - Does anyone have a best practice method for maintaining $(variables) in DBProj DDL / Schema scripts as per Remus answer and comment?