Is there anyway the conversion of a C # function to a sql server stored procedure?

I have a stored procedure that 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 any tool or at all that can convert this code to sql stored procedure code? Or do I need to rewrite it manually? The reason I'm asking is because, for example, I'm not sure how to handle the rotation of a dataset variable into sql type.

Thank!

Greg

+3
source share
3 answers

You will have to rewrite it manually. This is not too complicated.

For a loop through your datatable, you replace this 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;
+1
source

- , , # SQL.

+1

Using the sql server project in visual studio, you can change the existing C # code to a stored procedure.

Features decorated [Microsoft.SqlServer.Server.SqlProcedure]

And your function returns only sqlboolean type, if you want to use another type of return value, you use output parameters.

Check out http://blog.sqlauthority.com/2008/10/19/sql-server-introduction-to-clr-simple-example-of-clr-stored-procedure/

0
source

Source: https://habr.com/ru/post/1754216/


All Articles