3
Answers

How to capture stored procedure query or print output in C#

Sudipta Saha

Sudipta Saha

7y
175
1
I have a stored procedure like this
  1. PROCEDURE PRC_ABCD (resultset_out out TYPES.cursorType)  
  2. AS  
  3. SELECT * FROM ABCD;  
  4. END PRC_ABCD ;  
And my C# code is like this
  1. string cnn = "connectionstring";   
  2. OracleConnection conn = new OracleConnection(cnn);   
  3. conn.Open();   
  4. var cmd = adapter.CreateSpCommand(con, "PRC_ABCD");   
  5. cmd = adapter.outField(cmd, "resultset_out", OracleDbType.RefCursor);   
  6. using (var reader = cmd.ExecuteReader())   
  7. {   
  8.  while (reader.Read())   
  9.     {   
  10.        yield return Total.FromDataReader(reader, vProductCount, vProductAreaCount, vMonitoredByCount, customerCount);   
  11.  }  
  12. }  
My question is how do I get to see the results of PRC_ABCD into console message or how do I get to print the query SELECT * FROM ABCD?Anybody have any info about this?
Answers (3)
1
Dharmraj Thakur

Dharmraj Thakur

NA 4.1k 61.7k 7y
Hi Sudipta,

If you are looking to static print query then Change your stored procedure like below and featch that column in c# as usual...
  1. Declare @query as varchar(max);  
  2. set @query = 'SELECT * FROM ABCD';  
  3. select @query as query; 
0
Sudipta Saha

Sudipta Saha

NA 41 1.1k 7y
thanks for reply :) ..I dont have too much experience in C# and store procedure.once again thank you for guiding me :)
0
Suraj Kumar

Suraj Kumar

NA 1.3k 14.3k 7y

Attachment SP_Output.zip

Hi Sudipta,
You can write sql query as below and I have attached the source code also
-- ProcedureQueryOutput 'Suraj Kumar Mandal', ''
ALTER PROCEDURE [dbo].[ProcedureQueryOutput]
(
@EmpName VARCHAR(50),
@SQLQuery NVarchar(2000) out
)
AS
IF EXISTS ( SELECT * FROM EmpTable WHERE EmpName = @EmpName )
BEGIN
SET @SQLQuery = ('SELECT * FROM EmpTable WHERE EmpName =''' + @EmpName +'''')
END
ELSE
BEGIN
SET @SQLQuery = 'INSERT INTO EmpTable (EmpName) VALUES ( '''+ @EmpName +''' )'
END
EXECUTE sp_executesql @SQLQuery
And after that you can call in web form as below
protected void btnGetSQLText_Click(object sender, EventArgs e)
{
string message = String.Empty;
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=TestDB; User Id=sa; Password=password12");
con.Open();
SqlCommand cmd = new SqlCommand("ProcedureQueryOutput", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@EmpName", txtName.Text.Trim().Replace("'","''"));
cmd.Parameters.Add("@SQLQuery", SqlDbType.NVarChar, 500);
cmd.Parameters["@SQLQuery"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
message = (string)cmd.Parameters["@SQLQuery"].Value;
con.Close();
}