I'll admit, I haven't used the DB_NAME very often. I pretty much use it in a single scenario. With all of my projects I use Continuous Deployment or Continuous Integration, whatever your choice of word is. When doing CI I have automatic deployment of any database scripts that need to run as I deploy to each environment: local, development, production, etc.
On occasion, a script needs to apply a custom value for each environment like a user ID. To accomplish I use DB_NAME to perform a case statement as follows.
First I start by storing the name in a variable. Then I (typically) perform an update statement applying a case statement to specify the unique value per environment. You will need to know the database name of each environment:
In the example above, the table, field, database names, and the value will need to be updated to match your requirements. Published on Jan 31, 2020 Tags: SQL Tutorials for Beginners, Intermediate and Advanced Users
| DB_NAME
Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article
that you just finished reading.
No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner
or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in
and improve your skillset with any of the tutorials below.
Leveraging DB_NAME to apply custom logic
DECLARE @dbName nvarchar(128)
SELECT @dbName = DB_NAME()
UPDATE MyTable SET
ValueField =
CASE
WHEN 'LocalDatabase' THEN 1
WHEN 'DevelopmentDatabase' THEN 2
WHEN 'ProductionDatabase' THEN 3
END
Related Posts
Tutorials
Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.