views:

62

answers:

2

Hi,

I have a stored procedure which is written in c#:

SqlConnection scn = new SqlConnection("context connection=true;");
        SqlCommand scm = new SqlCommand("Select * from EPMS_Filters",scn);
        SqlDataAdapter sda = new SqlDataAdapter(scm);
        DataSet ds = new DataSet();


        //template for select Query.
        String SelectQry = "select convert(varchar,TimeStamp,101) as TimeStamp, avg({0} from EPMSDataTable  where timestamp between '{1}' and '{2}' group by convert(varchar,timestamp,101)";
        String filters = "";

        //select clause part which contains simple columns select col1, col2...
        sda.SelectCommand.CommandText = "Select column_name from information_schema.columns where table_name = 'EPMSDataTable' and column_name <> 'timestamp'";
        sda.Fill(ds, "SimpleFilters");
        foreach (DataRow dr in ds.Tables["SimpleFilters"].Rows)
        {
            String fName = dr[0].ToString();
            filters += dr[0] + ")as " + dr[0] + ", avg(";
        }

        filters = filters.TrimEnd(", avg(".ToCharArray()); //remove last ','

        scm.CommandText = String.Format(SelectQry,filters,start.ToString(),end.ToString());
        scn.Open();
        SqlContext.Pipe.Send(scm.ExecuteReader());
        scn.Close();

Is there anyway or some tool that can convert this code to an sql stored procedure code? Or do I have to rewrite it by hand? The reason I am asking is that for instance I am not sure how to handle the turn the dataset variable to sql type..

Thanks!

Greg

A: 

The answer is no, its unlikely that any automated process would be able to turn that C# into a SQL Stored procedure.

Jamiec
A: 

You'll have to rewrite it by hand. It's not too hard though.

For the loop through your datatable, you would replace that with a cursor, something like this:

SET NOCOUNT ON;

DECLARE ohno_a_cursor CURSOR FAST_FORWARD FOR 
Select column_name from information_schema.columns where table_name = 'EPMSDataTable' and column_name <> 'timestamp'

DECLARE @colname nvarchar(max);

OPEN ohno_a_cursor;
FETCH NEXT FROM ohno_a_cursor INTO @colname
WHILE @@FETCH_STATUS = 0 BEGIN
    SET @Filters = @Filters + '(whatever');
END

CLOSE ohno_a_cursor;
DEALLOCATE ohno_a_cursor;
Dave Markle