9

Is there a way to create a global variable in SQL Server, in such a way that it persists even if the server is restarted, so I can use it in functions?

Example from what I need:

DECLARE @@DefaultValue bit

This variable should never be deleted unless I explicityl do so.

4 Answers 4

10

I guess this will work the best for me:

CREATE FUNCTION [dbo].[fn_GetDefaultPercent]()
RETURNS decimal(5,4)
AS
BEGIN
    RETURN 1.0000
END
Sign up to request clarification or add additional context in comments.

3 Comments

How is this variable?
@CompanyDroneFromSector7G: You can use it variable-esque, like in conditionals, even though it’s merely a work-around for a non-existing feature.
@dakab A constant then, which I guess could go part way to a solution.
8

You can have a look at something like this

"Global variables" in SQL Server

3 Comments

Global variables are not persistent at all.
how would you use those global variables in a query?
This would be better as user-defined functions than stored procedures, particularly for use in a query, otherwise you have to add and assign a variable for each value used. Also, those prefixes are not a good idea: • sqlperformance.com/2012/10/t-sql-queries/sp_prefixdba.stackexchange.com/questions/154251/…github.com/red-gate/SQL-code-smells#namingxkcd.com/645
5

Not a global variable.

There's chance you can define a global UDF like you can create a "system" stored proc (starts "sp" in master), but I've not tried it.

Note:

Even DECLARE @@DefaultValue bit is actually local:

@ means local variable, identifier is @DefaultValue

It's not really global: try SELECT @@DefaultValue from 2 another query window

Comments

0

I know is answered but just for fun :)

How about a table with 2 columns like:

GLB_VARIABLES:
GLB_VAR_NAME varchar(100) PRIMARY KEY,
GLB_VAR_VALUE varchar(100)

1 Comment

Astander's answer links to an example of how to do this kind of thing robustly, and how to actually use them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.