SQL: avoiding hard-coding or magic numbers

后端 未结 11 1428
无人及你
无人及你 2020-12-14 17:18

Question: What are some other strategies on avoiding magic numbers or hard-coded values in your SQL scripts or stored procedures?

Consider a stored

11条回答
  •  一向
    一向 (楼主)
    2020-12-14 17:50

    Imagine

    table dbo.Status
    (
         Id int PK
        ,Description varchar
    )
    values
    1, Received
    2, Acknowledged
    3, Under Review
    etc
    

    So, just

    declare @StatusReceived int = 1
    declare @StatusAcknowledged int = 2
    declare @StatusUnderReview = 3
    etc
    

    As others mention, this assumes that IDENTITY is not set.

    I too used to JOIN on lookup tables, but this keeps the SELECT shorter and easier to read.

    This approach lends itself to automation, so I generate an entire table in a separate query, then copy over the elements I require (not all of them).

提交回复
热议问题