SQL Tip: Double Duty for DECLARE

Just recently, I realized that T-SQL allows variables to be declared and set with a single statement:

DECLARE @UserID int = 1592;

Up until this discovery, I only knew about the more traditional, two-step declaration and assignment syntax:

DECLARE @UserID int;
SET @UserID = 1592;

Moral of the Tip

How had I missed this inline assignment syntax? I’m not sure—perhaps because it didn’t exist when I studied T-SQL years ago. Regardless, recent poking around in MSDN documentation let me to this syntactical simplification.

You may say, “I’ve known that DECLARE can do double duty—simultaneous declaration and assignment—for a long time.” That’s great but don’t miss the bigger lesson of this tip:

Exploring documentation led to new knowledge. So, take a few minutes every now and then and read about a T-SQL statement or Microsoft SQL Server feature, even one you think you already know well. There might be something new you’ll pick up, just like I did!

Leave a Reply

Your email address will not be published. Required fields are marked *