Stored Procedures With optional parameters MVC4 - sql-server-2008

I have a stored procedure with some optional parameters.....I pass a type parameter and depending on that i invoke the appropriate query.
Following is my query
create procedure [dbo].[usp_InsertInfo]
#login_id varchar(500)=null,
#login_name varchar(200)=null,
#handler_name varchar(500)=null,
#city varchar(100)=null,
#email varchar(500)=null,
#img_url_http varchar(max)=null,
#img_url_https varchar(max)=null,
#token varchar(500)=null,
#login_type varchar(2)=null
as
begin
if(#login_type='F')
//code goes here
else
//code goes here
end
And here is the way i am calling it from my controller
using (Entities dbContext = new Entities())
{
var parameters = new SqlParameter[7];
parameters[0] = new SqlParameter { ParameterName = "login_id", Value = objUser.Id };
parameters[1] = new SqlParameter { ParameterName = "login_name", Value = objUser.Name };
parameters[2] = new SqlParameter { ParameterName = "handler_name", Value = objUser.ScreenName };
parameters[3] = new SqlParameter { ParameterName = "img_url_http", Value = objUser.ProfileImageUrl };
parameters[4] = new SqlParameter { ParameterName = "img_url_https", Value = objUser.ProfileImageUrlHttps };
parameters[5] = new SqlParameter { ParameterName = "token", Value = accessToken.Token };
parameters[6] = new SqlParameter { ParameterName = "login_type", Value = "T" };
List<userInfo> objUserInfo = dbContext.ExecuteStoreQuery<userInfo>("usp_InsertInfo #login_id,#login_name,#handler_name,#img_url_http,#img_url_https,#token,#login_type", parameters).ToList();
}
But when i check the values in Database the values are messed up...
In img_url_http i get the token value img_url_https i get the type value and so on.
M confused like where m i going wrong or wether MVC4 doesnot support null parameters.
Or please help me with the proper way of calling the stored procedure through MVC4 with optional parameters
I want to run this code with the optional parameters and execute the store procedure and return the results depending upon the conditions.

static void CallAProcedure(int required, int? optional)
{
string connectionstring = "connection string here.";
using (SqlConnection cn = new SqlConnection(connectionstring))
{
cn.Open();
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandText = "AProcedure";
cm.CommandType = CommandType.StoredProcedure;
cm.Parameters.AddWithValue("#Required", 1);
if (optional.HasValue)
cm.Parameters.AddWithValue("#Optional", optional.Value);
cm.ExecuteNonQuery();
}
}
}

Related

How to pass the output parameter for MySQL stored procedure for .net core using Pomelo ORM

Here is my SP in MySQL
CREATE PROCEDURE `GetMemberID`(
IN uname VARCHAR(128),
OUT MemberID INT
)
BEGIN
SELECT ID INTO MemberID FROM `Member` Where username = uname;
END
And I am calling SP from .netcore web api project that is using Pomelo ORM.
var usernameParam = new MySqlParameter
{
ParameterName = $"#uname",
DbType = DbType.String,
Direction = ParameterDirection.Input,
Value = "test"
};
var memberIDParam = new MySqlParameter
{
ParameterName = $"#MemberID",
DbType = DbType.Int32,
Direction = ParameterDirection.Output
};
rContext.Database.ExecuteSqlRaw($"Call GetMemberID (#uname=#uname, #MemberID=#MemberID OUT)"
, usernameParam , memberIDParam);
I am getting the following error when used output parameter.
Only ParameterDirection.Input is supported when CommandType is Text (parameter name: #MemberID)
How can I pass output parameter?
It's a known issue in github ,as mguinness commented
RelationalCommand.csdon't specify CommandType so it'll default to CommandType.Text which means output parameters won't work.
Here is a workaround ,you could refer to
using (MySqlConnection lconn = new MySqlConnection(Configuration.GetConnectionString("DefaultConnection")))
{
lconn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = lconn;
cmd.CommandText = "GetMemberID"; // The name of the Stored Proc
cmd.CommandType = CommandType.StoredProcedure; // It is a Stored Proc
cmd.Parameters.AddWithValue("#uname", "sherry");
cmd.Parameters.Add("#MemberID", MySqlDbType.Int32);
cmd.Parameters["#MemberID"].Direction = ParameterDirection.Output; // from System.Data
cmd.ExecuteNonQuery();
Object obj = cmd.Parameters["#MemberID"].Value;
var lParam = (Int32)obj; // more useful datatype
}
}
Reference :How to call stored procedure in Entity Framework Core with input and output parameters using mysql

Use DatabaseFactory to call Stored Procedure by passing TableType

I am getting error while trying to pass table type to Stored Procedure
Created datatable dataTableMyData with datatype name
DataTable dataTableMyData = new DataTable("myTableType");
My code :
DatabaseFactory.ClearDatabaseProviderFactory();
DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());
Database db = DatabaseFactory.CreateDatabase();
DataSet dsResult = new DataSet();
DbCommand cmd = db.GetStoredProcCommand("sp_Save_Clue_Auto_Response"))
db.AddInParameter(cmd, "#myTableType", System.Data.SqlDbType.Structured, dataTableMyData);
How to use the DatabaseFactory to pass table type. Please help me here.
Your code doesn't execute the command? Did you forget to post that in your sample?
DataTable table = new DataTable();
SqlDatabase database = (SqlDatabase) DatabaseFactory.CreateDatabase("DatabaseName");
DbCommand dbCommand = database.GetStoredProcCommand("[StoredProcName]");
database.AddInParameter(dbCommand, "#MyTvp",SqlDbType.Structured, table);
DataSet dataSet = database.ExecuteDataSet(dbCommand);
maybe not the best approach, but works:
-- Create the data type
CREATE TYPE dbo.PlantList AS TABLE
(
plant_code char(1) Not Null Primary Key
)
GO
extension method
public static class DatabaseExtensions
{
public static void AddTableTypeParameter<T>(this Database database, DbCommand command, string name, string sqlType, IEnumerable<T> values)
{
var table = new DataTable();
PropertyInfo[] members = values.First().GetType().GetProperties();
foreach (var member in members)
{
table.Columns.Add(member.Name, member.PropertyType);
}
foreach (var value in values)
{
var row = table.NewRow();
row.ItemArray = members.Select(m => m.GetValue(value)).ToArray();
table.Rows.Add(row);
}
var parameter = new SqlParameter(name, SqlDbType.Structured)
{
TypeName = sqlType,
SqlValue = table
};
command.Parameters.Add(parameter);
}
}
and call as follows:
database.AddTableTypeParameter(command, "#region_filter_plants", "dbo.PlantList", regionFilterPlants.Select(p => new { plant_code = p }));

Getting return value from dynamic sql from stored procedure (SQL Server and C# ADO.NET)?

I created a stored procedure to get return value from a dynamic sql. I get the following exception:
String[1]: the Size property has an invalid size of 0.
My proc:
CREATE proc [dbo].[Review_Get_PrePopValue](#sqlQuery nvarchar(500), #display nvarchar(200) OUTPUT)
as
EXEC sp_executesql #sqlQuery,
#display OUTPUT
My Code:
public string GetAnswerValue(string contentSQL, string parameter, string parameterValue)
{
string sqlstatement = contentSQL.Replace(parameter, parameterValue);
using (var conn = new SqlConnection(_connectionString))
{
string prePopValue;
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandType = CommandType.StoredProcedure;
comm.CommandText = "Review_Get_PrePopValue";
comm.Parameters.Add(new SqlParameter("#sqlQuery", SqlDbType.NVarChar)).Value = sqlstatement;
comm.Parameters.Add(new SqlParameter
{
Direction = ParameterDirection.Output,
ParameterName = "#display",
SqlDbType = SqlDbType.NVarChar
});
conn.Open();
comm.ExecuteNonQuery();
prePopValue = comm.Parameters["#display"].Value.ToString();
return prePopValue;
}
}
My sql string:
Select #display = Grant_Number From GMIS_Grants where grant_id=1
Direction = ParameterDirection.Output, ParameterName = "#display", Size = 200, SqlDbType = SqlDbType.NVarChar
Needed to set the size for nvarchar
From MSDN
For bidirectional and output parameters, and return values, you must set the value of Size.
Also, add this at the end of your SP.
SELECT #display;

Input string was not in a correct format

Can anyone please advise where i have gone wrong with the following method / stored proceedure? I keep getting the following error...
**
> Input string was not in a correct
**
This is the Stored proceedure i using and the method.
-- --------------------------------------------------------------------------------
-- Routine DDL
-- --------------------------------------------------------------------------------
DELIMITER $$
CREATE DEFINER=`Admin`#`%` PROCEDURE `test`(
IN p_idExceptionLog INT(32) ,
IN p_ExceptionDate DATETIME ,
IN p_User VARCHAR(45) ,
IN p_ExceptionMessage VARCHAR(4000)
)
BEGIN
INSERT INTO ExceptionLog
(
id ,
Date ,
User ,
Message
)
VALUES
(
p_idExceptionLog ,
p_ExceptionDate ,
p_User ,
p_ExceptionMessage
) ;
END
private void showErrorBox(String errorMsg, MessageBoxButtons btnokshow)
{
MessageBox.Show(errorMsg, "FS Manager Error", MessageBoxButtons.OK);
// write to DB
string username = System.Environment.UserName.ToString();
string timestamp = DateTime.Now.ToString();
// Locals
MySqlConnection NasDB = null;
// MySqlCommand inputError1 = new MySqlCommand();
MySqlCommand inputError = null;
int rows = 0;
string spName = "test";
try
{
//Instantiate the DB connection setting the conn string
using (NasDB = new MySqlConnection(getConnectionString(ConnectionType.NAS)))
{
// Instantiate the command object that will fire the SP.
using (inputError = new MySqlCommand(spName, NasDB))
{
// Finish setting up the command object
inputError.CommandType = CommandType.StoredProcedure;
// Set up the SP params.
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_idExceptionLog", MySql.Data.MySqlClient.MySqlDbType.Int32, (1)));
inputError.Parameters[0].Value = "";
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionDate", MySql.Data.MySqlClient.MySqlDbType.DateTime, (1)));
inputError.Parameters[1].Value = timestamp;
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_User", MySql.Data.MySqlClient.MySqlDbType.VarChar, (45)));
inputError.Parameters[2].Value = System.Environment.UserName.ToString();
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionMessage", MySql.Data.MySqlClient.MySqlDbType.VarChar, (4000)));
inputError.Parameters[3].Value = errorMsg;
// Now that the SP is completely set up and ready to go open the conn and fire the SP.
inputError.Connection.Open();
rows = inputError.ExecuteNonQuery();
// Close ASAP
inputError.Connection.Close();
}
}
}
catch (Exception ex)
{
//showErrorBox(ex.ToString());
throw ex;
}
}
Thanks
Err you are declaring paramter[0] (idExceptionLog) as an Int32 and then setting it to a string in your script? perhaps not setting it will help if it's supposed to be auto-generated or giving it a valid int value if you are manually generating it.
Worked the problem out.
private void showErrorBox(String errorMsg, MessageBoxButtons btnokshow)
{
MessageBox.Show(errorMsg, "FS Manager Error", MessageBoxButtons.OK);
// write to DB
string username = System.Environment.UserName.ToString();
string timestamp = DateTime.Now.ToString();
// Locals
MySqlConnection NasDB = null;
MySqlCommand inputError = null;
int rows = 0;
string spName = "ExceptionInsert";
try
{
//Instantiate the DB connection setting the conn string
using (NasDB = new MySqlConnection(getConnectionString(ConnectionType.NAS)))
{
// Instantiate the command object that will fire the SP.
using (inputError = new MySqlCommand(spName, NasDB))
{
// Finish setting up the command object
inputError.CommandType = CommandType.StoredProcedure;
// Set up the SP params.
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_idExceptionLog", MySql.Data.MySqlClient.MySqlDbType.Int32, (0)));
inputError.Parameters[0].Value = null;
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionDate", MySql.Data.MySqlClient.MySqlDbType.DateTime, (1)));
inputError.Parameters[1].Value = timestamp;
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_User", MySql.Data.MySqlClient.MySqlDbType.VarChar, (45)));
inputError.Parameters[2].Value = System.Environment.UserName.ToString();
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionMessage", MySql.Data.MySqlClient.MySqlDbType.VarChar, (4000)));
inputError.Parameters[3].Value = errorMsg;
// Now that the SP is completely set up and ready to go open the conn and fire the SP.
inputError.Connection.Open();
rows = inputError.ExecuteNonQuery();
// Close ASAP
inputError.Connection.Close();
}
}
}
catch (Exception ex)
{
//showErrorBox(ex.ToString());
throw ex;
}
}

The SqlParameterCollection only accepts non-null SqlParameter type objects, not MySqlParameter objects

I have created a method that will insert any exceptions thrown into a table on "ExceptionLog" on MySql server.
ExceptionLog Table format
idExceptionLog int (AI)
User (varchar 45)
ErrorMessage (varchart 4000)
The problem is i keep getting the following error. Does anyone know why?
The SqlParameterCollection only
accepts non-null SqlParameter type
objects, not MySqlParameter objects.
private void showErrorBox(String errorMsg, MessageBoxButtons btnokshow)
{
MessageBox.Show(errorMsg, "FS Manager Error", MessageBoxButtons.OK);
// write to DB
string username = System.Environment.UserName.ToString();
string timestamp = DateTime.Now.ToString();
// Locals
SqlConnection NasDB = null;
SqlCommand inputError = null;
int rows = 0;
string spName = "ExceptionInsert";
try
{
//Instantiate the DB connection setting the conn string
using (NasDB = new SqlConnection(getConnectionString(ConnectionType.NAS)))
{
// Instantiate the command object that will fire the SP.
using (inputError = new SqlCommand(spName, NasDB))
{
// Finish setting up the command object
inputError.CommandType = CommandType.StoredProcedure;
// Set up the SP params.
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("ExceptionDate", MySql.Data.MySqlClient.MySqlDbType.DateTime, (1)));
inputError.Parameters[0].Value = timestamp;
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("User", MySql.Data.MySqlClient.MySqlDbType.VarChar, (45)));
inputError.Parameters[1].Value = System.Environment.UserName.ToString();
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("ExceptionMessage", MySql.Data.MySqlClient.MySqlDbType.VarChar, (4000)));
inputError.Parameters[2].Value = errorMsg;
// Now that the SP is completely set up and ready to go open the conn and fire the SP.
inputError.Connection.Open();
rows = inputError.ExecuteNonQuery();
// Close ASAP
inputError.Connection.Close();
}
}
}
catch (Exception ex)
{
//showErrorBox(ex.ToString());
throw ex;
}
All the classes inside System.Data.SqlClient are used for SQL Server database & not mysql.
In your code, replace SqlCommand with MySqlCommand and SqlConnection with MySqlConnection.
EDIT: See this page for the classes, you could use in this case.
I have made some slight changes and am now getting the following error.
**
Input string was not in a correct
**
This is the Stored proceedure i using and the method.
-- --------------------------------------------------------------------------------
-- Routine DDL
DELIMITER $$
CREATE DEFINER=Admin#% PROCEDURE test(
IN p_idExceptionLog INT(32) ,
IN p_ExceptionDate DATETIME ,
IN p_User VARCHAR(45) ,
IN p_ExceptionMessage VARCHAR(4000)
)
BEGIN
INSERT INTO ExceptionLog
(
id ,
Date ,
User ,
Message
)
VALUES
(
p_idExceptionLog ,
p_ExceptionDate ,
p_User ,
p_ExceptionMessage
) ;
END
private void showErrorBox(String errorMsg, MessageBoxButtons btnokshow)
{
MessageBox.Show(errorMsg, "FS Manager Error", MessageBoxButtons.OK);
// write to DB
string username = System.Environment.UserName.ToString();
string timestamp = DateTime.Now.ToString();
// Locals
MySqlConnection NasDB = null;
// MySqlCommand inputError1 = new MySqlCommand();
MySqlCommand inputError = null;
int rows = 0;
string spName = "test";
try
{
//Instantiate the DB connection setting the conn string
using (NasDB = new MySqlConnection(getConnectionString(ConnectionType.NAS)))
{
// Instantiate the command object that will fire the SP.
using (inputError = new MySqlCommand(spName, NasDB))
{
// Finish setting up the command object
inputError.CommandType = CommandType.StoredProcedure;
// Set up the SP params.
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_idExceptionLog", MySql.Data.MySqlClient.MySqlDbType.Int32, (1)));
inputError.Parameters[0].Value = "";
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionDate", MySql.Data.MySqlClient.MySqlDbType.DateTime, (1)));
inputError.Parameters[1].Value = timestamp;
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_User", MySql.Data.MySqlClient.MySqlDbType.VarChar, (45)));
inputError.Parameters[2].Value = System.Environment.UserName.ToString();
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionMessage", MySql.Data.MySqlClient.MySqlDbType.VarChar, (4000)));
inputError.Parameters[3].Value = errorMsg;
// Now that the SP is completely set up and ready to go open the conn and fire the SP.
inputError.Connection.Open();
rows = inputError.ExecuteNonQuery();
// Close ASAP
inputError.Connection.Close();
}
}
}
catch (Exception ex)
{
//showErrorBox(ex.ToString());
throw ex;
}
}