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.

fableal
  • 1,577
  • 10
  • 24
Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632

4 Answers4

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
Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
8

You can have a look at something like this

"Global variables" in SQL Server

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
  • Global variables are not persistent at all. – Shimmy Weitzhandler Nov 30 '10 at 00:04
  • 1
    how would you use those global variables in a query? – Haoest Dec 10 '15 at 17:28
  • 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: • https://sqlperformance.com/2012/10/t-sql-queries/sp_prefix • https://dba.stackexchange.com/questions/154251/is-adding-the-tbl-prefix-to-table-names-really-a-problem • https://github.com/red-gate/SQL-code-smells#naming • https://xkcd.com/645/ – brianary Sep 12 '18 at 17:44
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

gbn
  • 422,506
  • 82
  • 585
  • 676
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)