Add and edit Windows environment variables

Windows environment variables are a great way to store server specific information that may be accessed from different systems on the server. Connection strings, folder paths and ip addresses are common examples of what may be suitable to store as environment variables on the server.

To add or edit a Windows environment variable, right click on “Computer” -> “Properties” -> “Advanced System Settings” -> “Environment Variables”:

Edit And Add System Variables
Edit And Add System Variables

The upper part of the window that opens is used to manage “User variables”. Those variables are unique per user, so use those if you want the environment variable to vary depending on current user. The lower part contains the “System Variables”. Those variables are set per server.

A user or system variable consists of a variable name (the key) and a value.

To use an environment variable in T-SQL, use the following script and replace the [YOUR_ENVIRONMENT_VARIABLE] with the name of the environment variable:

DECLARE @ENV_VAR VARCHAR(MAX)
CREATE TABLE #TMP_ENV_VAR (VALUE VARCHAR(MAX))
INSERT INTO #TMP_ENV_VAR EXEC xp_cmdshell 'echo %<YOUR_ENVIRONMENT_VARIABLE>%'
SELECT TOP 1 @ENV_VAR = VALUE FROM #TMP_ENV_VAR WHERE VALUE IS NOT NULL AND SUBSTRING(VALUE,1,1) <> '%' ORDER BY VALUE
DROP TABLE #TMP_ENV_VAR
SELECT @ENV_VAR

A couple of notes on the script.

  • The data type varchar(max) is used but the maximum number of characters on the value is 2048 on 64-bit Windows 7 (I actually tried…). The max number of characters on environment variables may vary depending on the os, that’s why I use the max value.
  • There are actually two rows returned by the echo command for some reason I don’t know. That’s why I filter out NULL values.
  • Finally, if no matching variable name is found by the echo command, your entered value name is returned. That’s why I filter out values starting with “%” as variable names do. The @ENV_VAR will in this case be NULL.
  • Tomas Lind

    Tomas Lind - Consulting services as SQL Server DBA and Database Developer at High Coast Database Solutions AB.

    Leave a Reply