Greg's Blog

helping me remember what I figure out

More Stored Procedures

| Comments

This time round I wanted to execute a query within my stored procedure (SP) and store the result in a variable that I could use at a later point in the SP. The idea is that you have to declare a variable that will hold the result (in this case @currentDay) and then you write your SQL like such: ”Select @currentDay = DATEPART(dw, GETDATE())” [incidentally I am grabbing the numeric day value, e.g. 1 which means Sunday]. Just to demonstrate the principle, below is some code that creates an SP, defines the expected inputs, declares a few variables, then executes the select statement, assigns the result to @currentDay and then prints it.

CREATE PROCEDURE [dbo].[qSomeSP] (
@someID int = NULL,
@someChar varchar(30) = NULL,
)
AS

DECLARE
@currentDay varchar(10)

Select @currentDay = DATEPART(dw, GETDATE())
PRINT(@currentDay)