Click here to Skip to main content
15,896,118 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
Hi I was trying to convert a scalar function in db to c#.

In db function was like this:This converts frequency to date for e.g
if frequency is monthly : 'M' and input is "2005 M1" (which is [Date] column), then it converts to 01-01-2005
SQL
CREATE FUNCTION [dbo].[funcFreqToDate]
(
    @Freq varchar(50),
    @InputVal varchar(255)
)
RETURNS varchar(255)
AS
BEGIN
    .
    IF @Freq = 'D' 
    	RETURN @InputVal;
    IF @Freq = 'A'
    	RETURN @InputVal +'-01-01';
    
    
    DECLARE @FreqToDate varchar(255)
    DECLARE @FreqInfo varchar(255);
    DECLARE @YearInfo varchar(255);
    DECLARE @FreqPos int;
    
    SET @FreqPos = CHARINDEX(@Freq,@InputVal);
    IF @FreqPos > 0
    	SET @FreqInfo = SUBSTRING(@InputVal,(@FreqPos+1),LEN(@InputVal));
    	SET @YearInfo = SUBSTRING(@InputVal,1,(@FreqPos-1))
    
    SET @FreqToDate = 
    	CASE 
    
    		WHEN @Freq='M' THEN @YearInfo +'-'+ cast((cast(@FreqInfo AS INT)) AS varchar(50)) + '-01'
    		ELSE @InputVal
    	END
    
    
    -- Return the result of the function
    RETURN @FreqToDate

It was called in c# as
C#
query = @"UPDATE " + srcDataTbl + @"
                SET [DateTransfrm] = CAST([dbo].funcFreqToDate([Frequency],[Date]) AS DATE)";

Please remember [Date] is varchar
[DateTransfrm] is of type Date

No i want to remove scalar function completely from db and move it into query in c#.

Can anyone help me write query for same in c#.
Thanks
Posted
Updated 4-May-15 23:22pm
v2
Comments
OriginalGriff 5-May-15 3:30am    
What have you tried?
Where are you stuck?
What help do you need?
glued-to-code 5-May-15 22:45pm    
I have tried moving scalar function logic completely to query. But i was not successful.
Sinisa Hajnal 5-May-15 3:37am    
And why would you move the function that works and lose time and potentially introduce the bugs into something that works? Instead move the call in C# to stored procedure, send source table, frequency and date as parameters.

Note that, depending on your srcDataTbl variable source, you're introducing potential SQL injection by directly concatenating into the query.
glued-to-code 5-May-15 22:47pm    
Ok, But recently we moved lot of such functions to c#
Tomas Takac 5-May-15 5:24am    
Do you realize that this scalar function is invoked for every row in "srcDataTbl"? You would have to read the whole table into memory set "DateTransfrm" row by row and then write back to the database.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900