This question already has answers here:
SQL : in clause in stored procedure:how to pass values
(8 answers)
Closed 7 years ago.
What I want to do :
Pass this parameter 'TV','OV','CK' as a single string into Stored Procedure (GetAllDataViaInQuery)
CREATE PROCEDURE GetAllDataViaInQuery #param varchar(240)
AS
BEGIN
SELECT TOP 100 [Model_No]
,[AppCode]
,[Model]
FROM [S_ModelMaster] where AppCode in (#param)
END
Then
I need to Pass parameter value via C# application as a single parameter.Because some time in values are may be vary.
Ex : string paramValue = "TV,OV,CK";
Then I wrote this C# code snippet.
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.Setting))
{
try
{
//hard coded parameter values
string paramValue = "TV,OV,CK";
con.Open();
DataSet ds = new DataSet();
SqlCommand com = new SqlCommand("GetAllDataViaInQuery", con);
com.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter("#param", paramValue);
com.Parameters.Add(param);
SqlDataAdapter adp = new SqlDataAdapter(com);
adp.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
But this is not work yet.
Then I execute Stored Procedure manually with SSMS.
DECLARE #return_value int
EXEC #return_value = [application].[GetAllDataViaInQuery]
#param = N'TV,OV,CK'
SELECT 'Return Value' = #return_value
But it's NOT WORKED!
Then I try it in sql query
SELECT TOP 100 [Model_No]
,[AppCode]
,[Model]
FROM [S_ModelMaster] where AppCode in ('TV','OV','CK')
And it's work.So what is the correct way to pass parameter to IN query in C#?
The way i see around this is, Use table valued parameters and send parameter in datatable format from c#.
And in Stored procedures something like select * from TableName where AppCode in(select parameter from tvpTable)
This is similar
Table valued parameters
Related
What I need:
In PLS/SQL on an Oracle DB, create a stored procedure or function with parameters, which given a declared table of , where is a ROW of a table (with all the fields), returns the resultset following the conditions given in the parameters. After, I need to call them from Microsoft Entity Framework with edmx file.
Basically the need is to being able to provide a quick report of the table contents into a pdf, matching some filters, with an oracle db.
The mantainer must be able, provided a script I give, to create and add new reports, so this needs to be dynamic.
Here's what I've got so far:
CREATE OR REPLACE type THETABLEIWANTTYPE as table of THETABLEIWANT%TYPE
create function
SCHEMA.THETABLEIWANT_FUNCTION(PARAM_GR in number default 1)
return THETABLEIWANTTYPE
PIPELINED
as
result_table THETABLEIWANTTYPE
begin
SELECT S.id, S.idg, S.sta, S.tab
Bulk collect into result_table
from SCHEMA.THETABLEIWANT S
WHERE IDGR = PARAM_GR
IF result_table.count > 0 THEN
for i in result_table.FIRST .. result_table.LAST loop
pipe row (result_table(i))
end loop
end if
return
end;
But it's not working. It gives errors.
Running CREATE TYPE I get:
Compilation errors for TYPE SCHEMA.THETABLEIWANT
Error: PLS-00329: schema-level type has illegal reference to
SCHEMA.THETABLEIWANT
The mantainer will launch the script creating a TYPE of the row of the table I need, then the function should return a table with the records.
Then calling it from Entity Framework I should be able to execute it like I'm calling a normal select from my table, IE:
``_dbContext.THETABLEIWANT.Where(x => x.IDGR = Param_gr).ToList();
The problem is that mantainers should be able to generate new kind of reports with any select inside without the need of my intervention on the software code.
Any hint?
It's ok also to bulk all the select result into a temp table but it has to be dynamic as column will be changing
I ended up to write a PLS/SQL procedure that returns a cursor and managing it from C# code with Oracle.ManagedDataAccess Library.
Here's the procedure, for anyone interested:
CREATE OR REPLACE PROCEDURE SCHEMA.PROC_NAME(
PARAM_1 VARCHAR2,
RESULT OUT SYS_REFCURSOR)
IS
BEGIN
OPEN RESULT FOR
SELECT A, V, C AS MY_ALIAS from SCHEMA.TABLE WHERE FIELD = PARAM_1 AND FIELD_2 = 'X';
END;
And here's the C# code for calling and getting the result:
OracleConnection conn = new OracleConnection("CONNECTIONSTRING");
try
{
if (conn.State != ConnectionState.Open)
conn.Open();
List<OracleParameter> parametri = new List<OracleParameter>()
{
new OracleParameter
{
ParameterName = nameof(filter.PARAM_1),
Direction = ParameterDirection.Input,
OracleDbType = OracleDbType.NVarchar2,
Value = filter.PARAM_1
}
};
OracleCommand cmd = conn.CreateCommand();
cmd.Parameters.AddRange(parametri.ToArray());
OracleParameter cursor = cmd.Parameters.Add(
new OracleParameter
{
ParameterName = "RESULT",
Direction = ParameterDirection.Output,
OracleDbType = OracleDbType.RefCursor
}
);
cmd.CommandText = procedureName;
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
using (OracleDataReader reader = ((OracleRefCursor)cursor.Value).GetDataReader())
{
if (reader.HasRows)
while (reader.Read())
{
//Iterate the result set
}
}
}
catch(Exception ex)
{
//Manage exception
}
I have the following Stored Procedure that receives a DataSet as parameter and Inserts into table Excel.
CREATE PROCEDURE spInsertInvoice
#tblInvoice InvoiceType READONLY
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Excel
SELECT Template, Cust_Name, Invoice_No,InvoiceDate FROM #tblInvoice
END
In my code file I am trying to read the Excel Sheet and filling the dataset. But problem is I am a bit confused as to how should I send the DataSet as Parameter to the stored Procedure.
This is what I have tried so far, but it doesn't seem to work
if (FileUpload1.HasFile)
{
string path = string.Concat((Server.MapPath("~/temp/" + FileUpload1.FileName)));
FileUpload1.PostedFile.SaveAs(path);
OleDbConnection oleCon = new OleDbConnection("Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + path + ";Extended Properties = Excel 12.0;");
OleDbCommand Olecmd = new OleDbCommand("select * from [Sheet1$]", oleCon);
OleDbDataAdapter dtap = new OleDbDataAdapter(Olecmd);
DataSet ds = new DataSet();
dtap.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
if (ds.Tables[0].Rows.Count > 0)
{
string consString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlCommand cmd = new SqlCommand("spInsertInvoice"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#tblInvoice", ds);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
When I execute it, it throws ArgumentException on cmd.ExecuteNonQuery()
No mapping exists from object type System.Data.DataSet to a known
managed provider native type.
You cannot pass dataset to stored procedure but you can pass datatable to stored procedure. Follow below algorithm to execute it:
1) Create Table type in sql server for the DataTable which you want to pass.
2) Declare input variable for given table type as readonly in stored procedure.
3) Pass that data table to procedure.
This only restricts your table type parameter sequence and datatable column sequence should be same.
You can refer this link Sending a DataTable to a Stored Procedure
Or Table-Valued Parameters
You can't parameterize your table name, basically.
Parameterized SQL is just for values - not table names, column names, or any other database objects. This is one place where you do probably want to build the SQL dynamically - but with a white-listed set of options or strong validation before you put this table name in your sql query.
It that line;
cmd.Parameters.AddWithValue("#tblInvoice", ds);
You try to pass your DataSet to your table name which does not make sense.
I have created a few stored functions in SQL Server that return a table via a select statement. Like so:
CREATE FUNCTION [dbo].[mFunSelectStudents] ()
RETURNS #result TABLE
(IDStudent int,
Name nchar(50),
Password nchar(50))
AS
BEGIN
INSERT INTO #result select * from School.dbo.Student
RETURN
END
I tried to assign the function to an SqlDataAdapter in c# like this:
SqlCommand cmd = new SqlCommand("mFunSelectStudents", con);
SqlDataAdapter adpStudents = new SqlDataAdapter();
adpStudents.SelectCommand = cmd;
But this doesn't work..
Where #result is a return parameter of the stored function. Now, how do I call the function in C# and assign the data to a grid ?
Any help is appreciated..
The command cannot be just the name of the function. You are supposed to put a SQL command there, and in SQL one retrieves data from a TVF by SELECTing from it, like this:
SELECT * FROM dbo.mFunSelectStudents()
Consequently, the first line of your C# code snippet should be:
SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.mFunSelectStudents()", con);
Wrap the function in a stored procedure, or do the work itself in a SP. The results of a single select statement will be accessible as a DataTable in the C# client.
create proc selectSomeData
.
.
.
In the client, your commandType would be StoredProcedure and the CommandText would be the name of the sp.
Your first line :
SqlCommand cmd = new SqlCommand("mFunSelectStudents", con);
Is correct, however this one you should check it
SqlDataAdapter adpStudents.SelectCommand = cmd;
First you need to use new with the SqlDataAdapter before you can assign the selectCommand, as follows:
SqlDataAdapter adpStudents = new SqlDataAdapter(cmd);
Assign the command to the DataAdapter
adpStudents.SelectCommand = cmd;
And then you prepare a Dataset
DataSet ds = new DataSet();
Fill it with your DataAdapter
adpStudents.Fill(ds);
Assign it to your grid
gridName.DataSource = ds;
And call DataBind to update the info on the grid
gridName.DataBind();
I have a procedure, I want to read schema of the procedure. To retrieve view schema I use the query shown here. Same way I want to get schema of stored procedure. How to get it? Plz show some syntax.
public static DataTable SchemaReader(string tableName)
{
string sql = string.Format("Select * from {0}", tableName);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataReader reader = cmd.ExecuteReader();
DataTable schema = reader.GetSchemaTable();
reader.Close();
conn.Close();
return schema;
}
If have any query plz ask.Thanks in advance.
you could do
public static DataTable SchemaReader(string tableName)
{
string sql = "MySP";//replace this with your store procedure name
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = cmd.ExecuteReader();
DataTable schema = reader.GetSchemaTable();
reader.Close();
conn.Close();
return schema;
}
Hope this help
This is an answer that does not call the SP - if you do, you may inadvertently affect data:
SELECT * FROM sys.dm_exec_describe_first_result_set ('owner.sprocName', NULL, 0) ;
This returns the result set :
is_hidden
column_ordinal
name
is_nullable
system_type_id
system_type_name
max_length
precision
scale
collation_name
user_type_id
user_type_database
user_type_schema
user_type_name
assembly_qualified_type_name
xml_collection_id
xml_collection_database
xml_collection_schema
xml_collection_name
is_xml_document
is_case_sensitive
is_fixed_length_clr_type
source_server
source_database
source_schema
source_table
source_column
is_identity_column
is_part_of_unique_key
is_updateable
is_computed_column
is_sparse_column_set
ordinal_in_order_by_list
order_by_is_descending
order_by_list_length
error_number
error_severity
error_state
error_message
error_type
error_type_desc
You could get information about a stored procedure's parameters but, without executing it, SQL Server cannot tell you the structure of the dataset(s) returned by the stored procedure. Since executing a stored procedure can have side effects, ADO.NET doesn't provide a method for telling you what the result set(s) would look like were the stored procedure to be executed. Furthermore, the result set(s) might change depending on the parameters passed to the procedure when it is executed.
I am not getting your question clearly I think this would work with you
Select *
from sys.objects
where type='p' and name = (procedure name)
Replace your query with this and it will work fine
I've created various code generators that use the output of stored procs. In my experience, most procedures that SELECT anything output their schema just the same if you call them with null (DbNull.Value) as the value for all parameters. You can get the parameter list itself from system views, though I find it convenient to use INFORMATION_SCHEMA.PARAMETERS.
By executing the procedure in a transaction and always rolling back you can safely execute stuff even when you have no idea what the procedure does.
You'll probably need a basic GUI and allow the user to modify the parameters - or a config file or some other way to provide parameter values for specific procedures. A stored proc may produce output with different schemas depending on the parameters, though I haven't seen many that do.
App.config
<appSettings>
<add key="Schema_Name" value ="[dev]."/> <!-- use any one [dev]. or [dbo]. -->
</appSettings>
c# read Key
string schema_Name = Configuration["Schema_Name"].ToString();
Store Procedure
SqlConnection objConn = new SqlConnection(Connection);
objConn.Open();
SqlCommand cmd = new SqlCommand("Exec WLTCVarification", objConn);
cmd.Parameters.Add("#SchemaName", SqlDbType.Text);
cmd.Parameters["#Schema_Name"].Value = schema_Name; // dev or dbo;
rowsAmount = (string)cmd.ExecuteScalar();
objConn.Close();
c# Sql Query
SqlConnection objConn = new SqlConnection(Connection);
objConn.Open();
SqlCommand cmd = new SqlCommand("select * from " + schema_Name + "receive_agv_onlyerror, objConn);
rowsAmount = (string)cmd.ExecuteScalar();
objConn.Close();
Can anyone tell me how I can control the output from an SQL stored procedure that returns more than one set of output?
I am currently doing the following:
DataTable allData = new DataTable();
SqlConnection connection = new SqlConnection(mySource);
SqlCommand cmd = new SqlCommand(procedureName, connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(paramName, SqlDbType.Int);
cmd.Parameters[paramName].Value = paramValue;
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(allData);
connection.Close();
Now this works fine if the procedure has only one output value, but how do I deal with the following:
My stored procedure broadly does the following:
It calls a number of other stored procedures in order to construct a dynamic SQL query (lets call this #query) and then calls EXECUTE(#query) which does a SELECT.
Using the code snippet above returns the result from the SELECT query, which is fine. But what I would also like it so have the string #query returned. I can specify it as an output type and let SQL fetch it, but how do I access it from c#? (Actually, more specifically, when I do this the code snipped above returns only the string #query and no longer returns the results of the SELECT)
Thanks
Karl
You can do like this:
DataSet allData = new DataSet ();
...
...
...
adapter.Fill(allData);
then each result of the select is in different dataTable
Using SqlDataReader.NextResult .
This little bit shifts you from using SqlDataAdapter, but you still is able to populate DataTable with DataTable.Load