简体   繁体   English

我可以在数据库的不同存储过程中引用SQL Server中的CONSTANT这样的东西吗?

[英]Is there such a thing as a CONSTANT in SQL Server that I can refer to in different stored procedures in my database?

I have this code which is part of a stored procedure. 我有此代码,它是存储过程的一部分。 I have other stored procedures with similar snippets. 我还有其他具有类似摘要的存储过程。

    INSERT INTO dbo.UserTest
    (  
        AdminTestId,
        Sequence,
        TestStatusId              
    ) 
    VALUES
    (
        @AdminTestId,
        @SEQ ,
        1
    ) 

Now I just realized the value of 1 should be a 2 for the testStatusId. 现在,我刚刚意识到testStatusId的值1应该是2 I keep making these mistakes as I forget which number is which. 我一直犯这些错误,因为我忘记了哪个号码。

Is there some way that I can have a constant that I could reference that would be set in one place outside all of the stored procedures? 有什么方法可以让我引用一个常量,该常量可以在所有存储过程之外的某个地方设置?

Ideally what I would like to do is something like this. 理想情况下,我想做的是这样的事情。 But I don't want to declare the value of TestStatusId.Started at the top of every stored procedure. 但是我不想在每个存储过程的顶部声明TestStatusId.Started的值。

    INSERT INTO dbo.UserTest
    (  
        AdminTestId,
        Sequence,
        TestStatusId              
    ) 
    VALUES
    (
        @AdminTestId,
        @SEQ ,
        @TestStatsusId.Started
    ) 

There is no concept of a constant in the context of a global value that can be referenced in your stored procedures. 在存储过程中可以引用的全局值的上下文中,没有常量的概念。 You can declare variables (although not constant) within your stored procedures: DECLARE @variableName <VariableType> = <Value> , but not outside of them. 您可以在存储过程中声明变量(尽管不是常量): DECLARE @variableName <VariableType> = <Value> ,但不能在DECLARE @variableName <VariableType> = <Value>之外。

The best option for having access to a value across multiple database objects is to create a table that contains your global values. 跨多个数据库对象访问值的最佳选择是创建一个包含全局值的表。 In your stored procedure, you can then use a SELECT statement to retrieve the value for you or create a user-defined function that pulls back a value by some key (eg by name). 然后,在存储过程中,可以使用SELECT语句为您检索值,或者创建一个用户定义的函数,该函数通过某个键(例如,按名称)拉回一个值。

There aren't 'constants' in the typical programming sense, but you're working in a database; 在典型的编程意义上没有“常数”,但是您正在数据库中工作。 your tables are filled with constants. 您的表中充满了常量。 If this is an issue for you, you could have a table that has the numeric identifier in one column and a keyword representation in the other. 如果这对您来说是个问题,则可以有一个表,其中一列包含数字标识符,另一列包含关键字。 Alternatively, you could have a function that does this conversion for you, and call it in the stored procedure. 另外,您可以使用一个函数为您执行此转换,然后在存储过程中调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM