I am trying to generate a dynamic SQL to assign variables with values from a function. I am trying to generate SQL something like
Select @StartDate=@EID_Dept
from dbo.WorkHistory(@today,@EID )
The function returns a date (@EID_dept will be the name of the column returned by the function) which I need to assign to @StartDate. And @EID_Dept is generated by concatenating @EID and @dept.
If I manually write the SQL it would appear as
Select @StartDate = amaan_IT
from dbo.WorkHistory('2016-10-10', amaan)
My code is below:
DECLARE @EID varchar(5), @StartDate VARCHAR(MAX),
@today DATETIME, @dept VARCHAR(10), @EID_dept varchar(20);
Select @today = SYSDATETIME()
Select @dept = dept from dbo.Dept(@EID)
Select @EID_Dept = CONCAT(@EID, @dept)
DECLARE @SQL Varchar(max);
SET @SQL = N'Select @StartDate = @EID_Dept
from dbo.PeriodHistory(@today, @EID)';
EXEC Sp_executesql
@SQL,
N'@StartDate VARCHAR(MAX) out,@EID_dept varchar(max),@today datetime,@EID Varchar',
@StartDate out,
@EID_Dept=@EID_Dept,
@today=@today
SET @SQL = CONCAT(N'SELECT @StartDate = ', @EID_Dept, ' FROM dbo.PeriodHistory(@Today, @EID);). This seems far from ideal though, I am not convinced that you are doing this the best way.