Quantcast
Channel: SQLServerCentral » SQL Server 2014 » Development - SQL Server 2014 » Latest topics
Viewing all articles
Browse latest Browse all 3145

How to Calculate the Values for a Column having Formulas , The Formula Variables being columns from the Same SQL Server Table

$
0
0
I have the table contents as shown in this picture:screenshot[img]https://i.stack.imgur.com/FAuzP.jpg[/img]The formula column contains the the column names as variables in the formula expression.I am trying to get a computed column Score corresponding for each emp_id,Tsk_id and processed date which would be calculated dynamically based on the formulae given in the formula column and push it to a temp tableI have tried to achieve it by dynamic SQL within a cursor using the below code which has been successful. Can Anyone suggest a better way to do it, maybe using a CTE or something ?DECLARE @EMP_ID nVARCHAR(255)DECLARE @TSK_ID nVARCHAR(255) DECLARE @PROCESSEDDATE nVARCHAR(255) DECLARE @SQLCMD nVARCHAR(max) DECLARE @SQLTEXT nvarchar(max)DECLARE db_cursor CURSOR FOR SELECT EMP_ID,TSK_ID,PROCESSEDDATE from dbo.[Formula_Cal] group by EMP_ID,TSK_ID,PROCESSEDDATEOPEN db_cursor FETCH NEXT FROM db_cursor INTO @EMP_ID,@TSK_ID,@PROCESSEDDATEWHILE @@FETCH_STATUS = 0 BEGIN Set @SQLTEXT = (Select formula from dbo.[Formula_Cal] where EMP_ID=@EMP_ID and TSK_ID =@TSK_ID and PROCESSEDDATE=@PROCESSEDDATE ) Set @SQLCMD ='select emp_id,TSK_ID,convert(decimal(18,2),( ' +@SQLTEXT+ ')) As Score FROM [Formula_Cal] where TSK_ID = '+@TSK_ID+' and EMP_ID = '+@EMP_ID --Select @SQLTEXT --Select @SQLCMD insert into dbo.TMP_ACHSCR(emp_id,TSK_id,Score) Exec sp_executesql @SQLCMD FETCH NEXT FROM db_cursor INTO @EMP_ID,@TSK_ID,@PROCESSEDDATE END CLOSE db_cursor DEALLOCATE db_cursor

Viewing all articles
Browse latest Browse all 3145

Trending Articles