How to get the return value from a dynamic SQL Stored Procedure executed with sp_executesql

Solution:

Example Stored Procedure.
Create procedure Test
(@ReturnValue Nvarchar(100)='')
as
begin
SET @ReturnValue = 'select ''hai'' ColumeName' 
execute SP_EXECUTESQL @ReturnValue
END
Execute Stored Procedure.
declare @ret int
exec sp_executesql N'exec @ret = Test', N'@ret int OUTPUT', @ret = @ret OUTPUT 
RESULT:

Get Values From C sharp.
try
            {
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }

                SqlCommand cmd = new SqlCommand("test", conn);

                cmd.CommandText = "declare @ret int exec sp_executesql N'exec @ret = Test1', N'@ret int OUTPUT',     @ret = @ret OUTPUT ";
                DateTime i = (DateTime)cmd.ExecuteScalar();

                //Return Datatable
                DataTable dt = new DataTable();
                SqlDataAdapter sda = new SqlDataAdapter(cmd.CommandText, conn);
                sda.Fill(dt);

               
            }
            catch
            {

            }
            finally
            {
                conn.Close();
            }
Download Sample Project.
VS 2013 with C charp

Post a Comment

3 Comments

  1. Is this for MSQL ?

    Just a suggest:
    for each example you should specify if the script is for mssql, mysql, oracle or others databases

    ReplyDelete