007. Select Into Variable

 

007. Select Into Variable

 

Often, in non-textbook situations, I’ve found I had to assign my variable from something that isn’t hard-coded. It might be from something I need to get from within the data itself. It might be something that keeps changing all the time, like a count. Or it might be something that is going to be different between Development and Production environments.

Insert dbo.tblCodeTable (CodeID, GroupID, Code) Values (1, ‘6’, ‘A’)
Insert dbo.tblCodeTable (CodeID, GroupID, Code) Values (2, ‘3’, ‘B’)
Insert dbo.tblCodeTable (CodeID, GroupID, Code) Values (3, ‘6’, ‘A’)
Insert dbo.tblCodeTable (CodeID, GroupID, Code) Values (4, ‘3’, ‘A’)
Insert dbo.tblCodeTable (CodeID, GroupID, Code) Values (5, ‘3’, ‘B’)
Insert dbo.tblCodeTable (CodeID, GroupID, Code) Values (6, ‘6’, ‘A’)

Select * From tblCodeTable

DECLARE @activeCode nvarchar(50)
SELECT @activeCode = Code FROM tblCodeTable WHERE CodeID = 6
SELECT @activeCode