Getting stored procedure script through C# in ASP .NET - c#

I am working on a DbCompre tool. Basically my requirement is that through C#, generate stored procedure script in web application. First of all is it possible?
In SQL Server we generate script easily through right click or with the help of command sp_helptext <ProcedureName>.
Here is my code:
public DataTable generateScripts()
{
SqlCommand cmd = new SqlCommand("sys.sp_helptext dloc_GetTasksRewarehousePutaway", AppCon);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(DS);
adp.SelectCommand = cmd;
return DS.Tables[0];
}
When code execute I am getting this error:
Could not find stored procedure 'sys.sp_helptext dloc_GetTasksRewarehousePutaway'
But in database this procedure is available.

Absolutely its possible, you need to pass the SP name as a parameter though to the parameter objname:-
SqlCommand cmd= new SqlCommand("sys.sp_helptext", AppCon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#objname", "dloc_GetTasksRewarehousePutaway");

using (SqlConnection con = new SqlConnection ("Connection String Here"))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "sp_helptext #procName";//Stored Procedure name
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("procName", "dloc_GetTasksRewarehousePutaway");
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
/*
You will get the CREATE PROC text here
Do what you need to with it. For example, write
to a .sql file
*/
}
}
}
}

Whole example to get stored procedure T-SQL text from database
// add connection string
var conString = "Db Connection String";
// add SP name
var spName = "DbSpName";
var sb = new StringBuilder();
try
{
using (var conn = new SqlConnection(conString))
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("sys.sp_helptext", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#objname",spName );
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
sda.SelectCommand = cmd;
var dt = ds.Tables[0];
foreach (DataRow dtRow in dt.Rows)
{
sb.Append(dtRow["Text"].ToString());
}
}
}
catch (Exception ex)
{
// log if something went wrong ex.Message
}

Related

Displaying results of query to Oracle database in dataGrid

I am struggling to make my dataGrid viev results of query. Connection with database is fine. Here is sample of my code:
using (OracleConnection conn = new OracleConnection())
{
conn.ConnectionString = "properConnectionString"
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select * FROM WORKERS";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
using (OracleDataAdapter orclDataAdapter = new OracleDataAdapter(cmd))
{
DataTable dt = new DataTable();
orclDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
}
}
Assuming that your call to the Oracle database is actually returning data, you're missing the databind statement on the gridview. Add this:
dataGridView1.DataBind();
place it right after the dataGridView1.DataSource = dt; line of code.

C# InvalidOperationException when creating a new SqlDataAdapter

I`ve written some code to establish a connection to SQL Server, then execute select procedure to take all data from my data table in SQL server, but it throw a InvalidOperationException at the command of declare a new SqlDataAdapter, please help me to fix this error.
public class dBConnect
{
//create SQLconnection variable
private SqlConnection con;
//create default constructor that passing a string to con
public dBConnect()
{
try
{
con = new SqlConnection(#"Server=Trump\SQLEXPRESS;
Database=Demo;User Id=sa;Password = stevejobs;");
}
catch(Exception exCon)
{
Console.WriteLine("Unable to connect to database: {0}", exCon);
}
}
//create Select method to Pour the data into the DataTable
public DataTable SelectAll(string procName, SqlParameter[] para = null)
{
//create a DataTable to store Data from DB
DataTable dt = new DataTable();
//create SQLCommand
SqlCommand cmd = new SqlCommand(procName, con);
//declare that cmdType is sp
cmd.CommandType = CommandType.StoredProcedure;
//input parameter of cmd
if (para != null)
cmd.Parameters.AddRange(para);
//create dataAdapter object
//InvalidOperationException was thrown at here
SqlDataAdapter da = new SqlDataAdapter(cmd);
//declare that cmd is select command of da
da.SelectCommand = cmd;
//use try/catch/finally to establish a connection
try
{
con.Open();
da.Fill(dt);
}
catch(Exception sqlEx)
{
Console.WriteLine(#":Unable to establish a connection: {0}", sqlEx);
}
finally
{
con.Close();
con.Dispose();
}
return dt;
}
}
}
You should:
cmd.CommandText = "your Stored Procedure here.";
cmd.CommandType = CommandType.StoredProcedure;
//input parameter of cmd
if (para != null)
cmd.Parameters.AddRange(para);
//create dataAdapter object
Put your con.Open(); above
or
Just take a look at this steps
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
//sample stored procedure with parameter:
// "exec yourstoredProcedureName '" + param1+ "','" + param2+ "'";
cmd.CommandText = "Your Stored Procedure Here";
cmd.CommandType =CommandType.StoredProcedure;
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(dt);
return dt;
}
}
}
Cleaning up your code a bit here:
public DataTable SelectAll(string procName, SqlParameter[] para = null)
{
DataTable dt = new DataTable();
try
{
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(procName, con))
{
cmd.CommandType = CommandType.StoredProcedure;
if (para != null)
cmd.Parameters.AddRange(para);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
}
catch (Exception sqlEx)
{
Console.WriteLine(#":Unable to establish a connection: {0}", sqlEx);
}
return dt;
}

How to use DataAdapter to call a stored procedure in C# with variable parameters

I am calling the following code in C# to fill a dataAdapter with a given stored procedure "sp1_name". The problem is that I want to call different stored procedures with different parameters. (All SP's do a SELECT)
Let's suppose that my stored procedure name is "SP_SOMESP", then everything works fine.
Let's suppose that my stored procedure name is "SP_SOMESP #Month= 10, #Year = 2010", then it doesn't work. It throws an exception that cannot find this stored procedure.
Any solutions?
Thanks!
//First Connection - SP1
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sp1_name, con)) //sp1_name = NAME + PARAMETERS
{
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
{
dataAdapter.Fill(results2);
}
}
}
First Issue:
Parameters in a stored procedure shouldn't be included along with its name
Second Issue:
Having a space in names of stored procedure isn't a good practice.
And for code behind
using(SqlConnection con = new SqlConnection("Your Connection String Here"))
{
SqlCommand cmd = new SqlCommand("sp_SomeName", con);
cmd.CommandType = CommandType.StoredProcedure;
//the 2 codes after this comment is where you assign value to the parameters you
//have on your stored procedure from SQL
cmd.Parameters.Add("#MONTH", SqlDbType.VarChar).Value = "someValue";
cmd.Parameters.Add("#YEAR", SqlDbType.VarChar).Value = "SomeYear";
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataSet ds = new SqlDataSet();
da.Fill(ds); //this is where you put values you get from the Select command to a
//dataset named ds, reason for this is for you to fetch the value from DB to code behind
foreach(DataRow dr in ds.Tables[0].Rows) // this is where you run through the dataset and get values you want from it.
{
someTextBox.Text = dr["Month"].ToString(); //you should probably know this code
}
}
You have to add in the parameters programmatically, see SqlCommand.Parameters.
It would be something like
cmd.Parameters.AddWithValue("#Month", 10);
cmd.Parameters.AddWithValue("#Year", 2010);
This would be after the command is declared and before it is executed.
If you find that you need to delcare the data type, then try it this way
cmd.Parameters.Add("#Month", SqlDbType.Int).Value = 10;
Check this,
using (SQLCommand cmd = new SQLCommand())
{
cmd.CommandText = "SP_SOMESP";
cmd.Parameters.Add("#Month", 10);
cmd.Parameters.Add("#Year", 2010);
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
}
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
{
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(results2);
}

C# and SQL Server: How do I get values from my SQL Table, by calling my stored procedure with C#?

I created the following stored procedure
CREATE PROCEDURE dbo.GetPoint
AS
SELECT point FROM tLocalGeo
Now I need execute that procedure from my C# Controller and save the data on a list.
As you can see the context of the problem is to get points so then I can display them on google map using javascript for that.
Can you give me some reference how to do it? Do I need SQLReader?
Thank you for your attention.
You can use SqlDataAdapter and DataSet and then can get values from dataset's first table.
SqlCommand cmd = new SqlCommand("store procedure Name", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter= new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
if(ds.Tables[0]!=null && ds.Tables[0].Rows.Count > 0)
{
//your code
}
Hope it helps.
String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetPoint";
cmd.Parameters.AddWithValue("#EmployeeID", Empid) // ur input parameter//
cmd.Connection = con;
try
{
con.Open();
GridView1.EmptyDataText = "No Records Found";
GridView1.DataSource = cmd.ExecuteReader() ;
GridView1.DataBind();
}

How can I retrieve a table from stored procedure to a datatable?

I created a stored procedure so as to return me a table.
Something like this:
create procedure sp_returnTable
body of procedure
select * from table
end
When I call this stored procedure on the frontend what code do I need to write to retrieve it in a datatable object?
I wrote code something like the following. I basically want to know retrieving and storing table into an object of datatable. All my queries are running, but I don't know how to retrieve table into a datatable through a stored procedure
DataTable dtable = new DataTable();
cmd.Connection = _CONN;
cmd.CommandText = SPNameOrQuery;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
OpenConnection();
adp.Fill(dtTable);
CloseConnection();
Here in this code a command has been bound with the stored procedure name and its parameters. Will it be returning me a datatable from the stored procedure?
string connString = "<your connection string>";
string sql = "name of your sp";
using(SqlConnection conn = new SqlConnection(connString))
{
try
{
using(SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = new SqlCommand(sql, conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds, "result_name");
DataTable dt = ds.Tables["result_name"];
foreach (DataRow row in dt.Rows) {
//manipulate your data
}
}
}
catch(SQLException ex)
{
Console.WriteLine("SQL Error: " + ex.Message);
}
catch(Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
Modified from Java Schools Example
Set the CommandText as well, and call Fill on the SqlAdapter to retrieve the results in a DataSet:
var con = new SqlConnection();
con.ConnectionString = "connection string";
var com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "sp_returnTable";
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);
(Example is using parameterless constructors for clarity; can be shortened by using other constructors.)
Explaining if any one want to send some parameters while calling stored procedure as below,
using (SqlConnection con = new SqlConnection(connetionString))
{
using (var command = new SqlCommand(storedProcName, con))
{
foreach (var item in sqlParams)
{
item.Direction = ParameterDirection.Input;
item.DbType = DbType.String;
command.Parameters.Add(item);
}
command.CommandType = CommandType.StoredProcedure;
using (var adapter = new SqlDataAdapter(command))
{
adapter.Fill(dt);
}
}
}

Categories