简体   繁体   中英

Is there a scalar database variable in SQL Server?

We are creating a schema version for our database. Right now we have a database table with a column version and a single row with the version.

Is it possible to make a scalar variable on the database, rather than a table?

Something like:

SET DBNAME.dbo.DBVersion = 1;

You may consider to store a scalar value in an Extended Property attached to your database.

To add an extended property use sp_addextendedproperty

EXEC sp_addextendedproperty @name = N'DBVersion', @value = '1';

To get a value of your property fn_listextendedproperty

SELECT value FROM fn_listextendedproperty(N'DBVersion', default, default, default, default, default, default);

Output:

Value
-----
    1

Further reading:

When I need to store constant values somewhere in the database for that that's not necessarily related I usually end up with dbo.Config table that has one column for each cost that it needs to hold.

If you really want to store this somewhere outside the table you can consider extended properties, views, functions or stored procedures.

You can always create a function that looks like

CREATE FUNCTION dbo.GetSomeConst ()
RETURNS int
BEGIN
    return 12
END

For static (read-only) data, you can also define a single-row view:

CREATE VIEW V_Constants AS
SELECT '1' AS DBVersion

as sketched in an earlier answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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