I have a this SQL Server stored procedure. When I execute it, I'm getting this error:
SQL Server procedure has too many arguments specified
How can I solve this problem? Code is shown below.
When my stored procedure is working, I need to do if record exist update then add record.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Insert_MS]
(#SID char(20),
#CREATE_DATETIME char(14),
#MODIFY_DATETIME char(14),
#CREATOR_SID char(20),
#MODIFIER_SID char(20),
#MARK_DELETED char(1),
#TARGET_SID nvarchar(20),
#TARGET_CODE nvarchar(50),
#UNIT nvarchar(100),
#SPECIFICATION nvarchar(1000),
#MATERIALS_SUBCAT nvarchar(1000),
#SORT int,
#SET_UNIT nvarchar(1000),
#ENABLED char(1),
#MARKET_TYPE nvarchar(2)
)
AS
BEGIN
IF EXISTS (SELECT *
FROM [dbo].[M_S]
WHERE [MARKET_TYPE] = #MARKET_TYPE
AND [TARGET_CODE] = #TARGET_CODE
AND [TARGET_SID] = #TARGET_SID)
BEGIN
--update existing record
UPDATE [dbo].[M_S]
SET [MATERIALS_SUBCAT] = #MATERIALS_SUBCAT ,
[SPECIFICATION] = #SPECIFICATION,
[UNIT] = #UNIT
WHERE [MARKET_TYPE] = #MARKET_TYPE
AND [TARGET_CODE] = #TARGET_CODE
AND [TARGET_SID] = #TARGET_SID
END
ELSE
BEGIN
--insert new record
INSERT INTO [dbo].[M_S] ([SID], [CREATE_DATETIME], [MODIFY_DATETIME],
[CREATOR_SID], [MODIFIER_SID], [MARK_DELETED],
[TARGET_SID], [TARGET_CODE], [UNIT], [SPECIFICATION],
[MATERIALS_SUBCAT], [SORT], [SET_UNIT],
[ENABLED], [MARKET_TYPE])
VALUES (#SID, #CREATE_DATETIME, #MODIFY_DATETIME,
#CREATOR_SID, #MODIFIER_SID, #MARK_DELETED,
#TARGET_SID, #TARGET_CODE, #UNIT,
#SPECIFICATION,
#MATERIALS_SUBCAT, #SORT, #SET_UNIT,
#ENABLED, #MARKET_TYPE)
END
END
Then my aspx.cs code is here
cnn.Open();
insertSql += " INSERT INTO [dbo].[MATERIALS_SUBCAT] ([SID],[CREATE_DATETIME], [MODIFY_DATETIME],";
insertSql += " [CREATOR_SID], [MODIFIER_SID], [MARK_DELETED],[TARGET_SID], [TARGET_CODE],";
insertSql += " [UNIT], [SPECIFICATION], [MATERIALS_SUBCAT], [SORT],[SET_UNIT], [ENABLED], [MARKET_TYPE])";
insertSql += " VALUES (#SID, #CREATE_DATETIME, #MODIFY_DATETIME, #CREATOR_SID, #MODIFIER_SID, #MARK_DELETED, #TARGET_SID, #TARGET_CODE, #UNIT, #SPECIFICATION,";
insertSql += "#MATERIALS_SUBCAT, #SORT, #SET_UNIT, #ENABLED, #MARKET_TYPE) ";
SqlCommand cmdStoredProcedure = new SqlCommand("Insert_MS", cnn);
cmdStoredProcedure.CommandType = CommandType.StoredProcedure;
for (int k = 0; k <= dt_sheet.Rows.Count - 1; k++)
{
cmdStoredProcedure.Parameters.AddWithValue("#SID", dt_sheet.Rows[k]["SID"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#CREATE_DATETIME", dt_sheet.Rows[k]["CREATE_DATETIME"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#MODIFY_DATETIME", dt_sheet.Rows[k]["MODIFY_DATETIME"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#CREATOR_SID", dt_sheet.Rows[k]["CREATOR_SID"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#MODIFIER_SID", dt_sheet.Rows[k]["MODIFIER_SID"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#MARK_DELETED", dt_sheet.Rows[k]["MARK_DELETED"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#TARGET_SID", dt_sheet.Rows[k]["分類代碼"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#TARGET_CODE", dt_sheet.Rows[k]["品項代碼"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#UNIT", dt_sheet.Rows[k]["單位"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#SPECIFICATION", dt_sheet.Rows[k]["規格"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#MATERIALS_SUBCAT", dt_sheet.Rows[k]["品項名稱"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#SORT", dt_sheet.Rows[k]["SORT"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#SET_UNIT",null);
cmdStoredProcedure.Parameters.AddWithValue("#ENABLED", dt_sheet.Rows[k]["ENABLED"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#MARKET_TYPE", dt_sheet.Rows[k]["MARKET_TYPE"].ToString());
cmdStoredProcedure.ExecuteNonQuery();
cnn.Close();
}
Seems like you want to execute the stored procedure each time you loop through your sheet. Moving the Command into the loop and use "using" to easy dispose the command each time, like this:
for (int k = 0; k <= dt_sheet.Rows.Count - 1; k++)
{
using (SqlCommand cmdStoreProcedure = new SqlCommand("Insert_MS", cnn))
{
cmdStoreProcedure.CommandType = CommandType.StoredProcedure;
cmdStoreProcedure.Parameters.AddWithValue("#SID", dt_sheet.Rows[k]["SID"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#CREATE_DATETIME", dt_sheet.Rows[k]["CREATE_DATETIME"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#MODIFY_DATETIME", dt_sheet.Rows[k]["MODIFY_DATETIME"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#CREATOR_SID", dt_sheet.Rows[k]["CREATOR_SID"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#MODIFIER_SID", dt_sheet.Rows[k]["MODIFIER_SID"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#MARK_DELETED", dt_sheet.Rows[k]["MARK_DELETED"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#TARGET_SID", dt_sheet.Rows[k]["分類代碼"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#TARGET_CODE", dt_sheet.Rows[k]["品項代碼"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#UNIT", dt_sheet.Rows[k]["單位"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#SPECIFICATION", dt_sheet.Rows[k]["規格"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#MATERIALS_SUBCAT", dt_sheet.Rows[k]["品項名稱"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#SORT", dt_sheet.Rows[k]["SORT"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#SET_UNIT", null);
cmdStoreProcedure.Parameters.AddWithValue("#ENABLED", dt_sheet.Rows[k]["ENABLED"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#MARKET_TYPE", dt_sheet.Rows[k]["MARKET_TYPE"].ToString());
// connection.Open();
cmdStoreProcedure.ExecuteNonQuery();
}
}
cnn.Close();
Your code tries to access SQL Commmand: Insert_Materials_SubCategory
Whereas the shown procedure is called: Insert_MS
Related
I calling a stored procedure and it has an int return value. However there is an error on returning the value back to my back end.
public async Task<string> CreatePortfolio(Portfolio portfolio)
{
string statusMessage;
using (SqlConnection conn = new SqlConnection(Connection))
{
SqlParameter returnValue = new SqlParameter(); //Holds the bit that determines if insert was successful or not
SqlCommand command;
command = new SqlCommand();
command.Connection = conn;
conn.Open();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "USP_Add_Portfolio";
command.Parameters.AddWithValue("#portfolioName", portfolio.PortfolioName);
command.Parameters.AddWithValue("#description", portfolio.Description);
command.Parameters.AddWithValue("#createID", portfolio.CreateID);
command.Parameters.AddWithValue("#updateID", portfolio.UpdateID);
command.Parameters.AddWithValue("#statusMessage", SqlDbType.NVarChar).Direction = ParameterDirection.Output;
returnValue.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(returnValue);
int i = await command.ExecuteNonQueryAsync().ConfigureAwait(false);
if(i == 1)
{
statusMessage = command.Parameters["#statusMessage"].Value.ToString();
}
else
{
statusMessage = "Error while adding please contact your administrator";
}
}
return statusMessage;
}
This is the stored procedure:
create procedure USP_Add_Portfolio
(#portfolioName as nchar(30) = null,
#description as nvarchar(200) = null,
#createID as nvarchar(40) = null,
#updateID as nvarchar(40) = null,
#statusMessage as nvarchar(max) output)
as
declare #success as int = 0
if #portfolioName is null
raiserror('Stored procedure USP_Add_Portfolio - Missing Parameter #portfolioName', 16,1)
else if exists( select * from Portfolio where [Portfolio_Name] = #portfolioName COLLATE SQL_Latin1_General_CP1_CI_AS)
begin
set #statusMessage = rtrim(#portfolioName) + ' already exists please try another portfolio name'
raiserror('Stored procedure USP_Add_Portfolio - Already exists #portfolioName', 16,1)
return 0
end
else if #createID is null
raiserror('Stored procedure USP_Add_Portfolio - Missing Parameter #Create_ID', 16,1)
else if #updateID is null
raiserror('Stored procedure USP_Add_Portfolio - Missing Parameter #Update_ID', 16,1)
else
begin
insert into Portfolio ([Portfolio_Name], [Long_Description], [Create_ID], [Create_TS], [Update_ID], [Update_TS])
values (#portfolioName, #description, #createID, getdate(), #updateID, getdate())
--Check to see if insert worked
set #statusMessage = case when ##ROWCOUNT = 1 then 'Successfully added ' + #portfolioName else 'Unable to add please try again' end
set #success = case when ##ROWCOUNT = 1 then 1 else 0 end
end
return #success
go
The stored procedure finishes and it adds the new record but it errors on
int i = await command.ExecuteNonQueryAsync().ConfigureAwait(false);
Error:
expecting an int but gets nvarchar
ExecuteNonQuery (not worrying about the async for the moment...) returns the number of rows affected for UPDATE, INSERT, DELETE, and -1 otherwise. It does NOT return information directly from the stored procedure.
In your case above, I think you should call the "await" without the "int i =" and not worry about the return value from the ExecuteNonQueryAsync call. Instead, after the value, look at the value in returnValue.Value, which would be the value of the "return" parameter. It is an object, so verify the type or use Convert.ToInt32().
This doesn't look correct because SqlDbType.NVarChar is an enumeration value:
command.Parameters.AddWithValue("#statusMessage", SqlDbType.NVarChar).Direction = ParameterDirection.Output;
What happens if you use this instead:
command.Parameters.Add(new SqlParameter("#statusMessage", SqlDbType.NVarChar, -1)).Direction = ParameterDirection.Output;
in a c# application, I need to insert into sql server 2005 table a lot or records. I split datatable in 2000 records chunk, using linq to sql server but dont work good becasue dont stop ever! I've 900.000 recors and insert a lot more thant this. What I'm doing wrong?
This is my code:
int jump = 0;
while (ds.Tables[0].Rows.Count < ds.Tables[0].Rows.Count + 1)
{
String xmlData = ConvertDataTableToXML(ds.Tables[0].AsEnumerable().Skip(jump).Take(2000 + jump).CopyToDataTable());
jump = jump + 2001;
SqlConnection conn = new SqlConnection
("Data Source=SERVER;Initial Catalog=DATABASE;Persist Security Info=True;User ID=USER;Password=PASS;");
conn.Open();
SqlCommand insert = new SqlCommand
("sp_InsertData'" + xmlData + "'", conn);
insert.ExecuteNonQuery();
conn.Close();
}
if you understand Temp Tables in SQL Server as well as how to use the OPENXML command you can try the following. it works even if your DBA disables BULK INSERTS
substitute my field names with your own and the field mappings in this portion of the code should match your tables schema / field definitions / data types
FROM OPENXML (#xmlHandle, '/NewDataSet/XMLDataTable',1)
WITH (
ALTER PROCEDURE [dbo].[sp_InsertData]
(#xmlString VARCHAR(MAX))
AS
BEGIN
/* Initialize a handle for the XmlDocument */
DECLARE #xmlHandle INT
/*
Created by #MethodMan you first want to create / declare a TEMP TABLE which
Mimic's the structure of the Target table that you are inserting into
*/
DECLARE #someTargetTable TABLE
(
[EN_INTFC_ID] varchar(25),
[EN_INTFC_LINE_NUM] varchar(5),
[EN_BILL_SOURCE_ID] varchar(10),
[EN_BUSINESS_UNIT] varchar(12),
[EN_ASSET_NAME] varchar(4),
[EN_POSTING_DATE] DateTime,
[EN_FISCAL_YEAR] varchar(4),
[EN_FISCAL_PERIOD] varchar(3),
[EN_CUSTOMER_ID] varchar(50),
[EN_DOC_TYPE] varchar(4),
[EN_TARGET_INVOICE] varchar(16),
[EN_INVOICE_DT] DateTime,
[EN_REVNUE_TYPE] varchar(15),
[EN_QTY] decimal(15,0),
[EN_GROSS_EXT_AMT] decimal(25,2),
[EN_DESCR] varchar(50),
[EN_CONTRACT] varchar(20),
[EN_PRODUCT_TYPE] varchar(15),
[EN_UNIT_OF_MEASURE] varchar(3)
)
/*
Create the XmlDocument using the handle above and the Xml
string as parameters. If your stored procedure has an varchar input
parameter named #xmlString, it would look like this instead:
EXEC sp_xml_preparedocument #xmlHandle output,#xmlString
*/
EXEC sp_xml_preparedocument #xmlHandle output, #xmlString
/*
Use the OPENXML method to query the XmlDocument starting at
/NewDataSet/SampleDataTable node.
*/
INSERT INTO #someTargetTable
SELECT [EN_INTFC_ID],
[EN_INTFC_LINE_NUM],
[EN_BILL_SOURCE_ID],
[EN_BUSINESS_UNIT],
[EN_ASSET_NAME],
[EN_POSTING_DATE],
[EN_FISCAL_YEAR],
[EN_FISCAL_PERIOD],
[EN_CUSTOMER_ID],
[EN_DOC_TYPE],
[EN_TARGET_INVOICE],
[EN_INVOICE_DT],
[EN_REVNUE_TYPE],
[EN_QTY],
[EN_GROSS_EXT_AMT],
[EN_DESCR],
[EN_CONTRACT],
[EN_PRODUCT_TYPE],
[EN_UNIT_OF_MEASURE]
FROM OPENXML (#xmlHandle, '/NewDataSet/XMLDataTable',1)
WITH (
[EN_INTFC_ID] varchar(25) '#EN_INTFC_ID',
[EN_INTFC_LINE_NUM] varchar(5) '#EN_INTFC_LINE_NUM',
[EN_BILL_SOURCE_ID] varchar(10) '#EN_BILL_SOURCE_ID',
[EN_BUSINESS_UNIT] varchar(12) '#EN_BUSINESS_UNIT',
[EN_ASSET_NAME] varchar(4) '#EN_ASSET_NAME',
[EN_POSTING_DATE] DateTime '#EN_POSTING_DATE',
[EN_FISCAL_YEAR] varchar(4) '#EN_FISCAL_YEAR',
[EN_FISCAL_PERIOD] varchar(3) '#EN_FISCAL_PERIOD',
[EN_CUSTOMER_ID] varchar(50) '#EN_CUSTOMER_ID',
[EN_DOC_TYPE] varchar(4) '#EN_DOC_TYPE',
[EN_TARGET_INVOICE] varchar(16) '#EN_TARGET_INVOICE',
[EN_INVOICE_DT] DateTime '#EN_INVOICE_DT',
[EN_REVNUE_TYPE] varchar(15) '#EN_REVNUE_TYPE',
[EN_QTY] decimal(15,0) '#EN_QTY',
[EN_GROSS_EXT_AMT] decimal(25,2) '#EN_GROSS_EXT_AMT',
[EN_DESCR] varchar(50) '#EN_DESCR',
[EN_CONTRACT] varchar(20) '#EN_CONTRACT',
[EN_PRODUCT_TYPE] varchar(15) '#EN_PRODUCT_TYPE',
[EN_UNIT_OF_MEASURE] varchar(3) '#EN_UNIT_OF_MEASURE'
)
/*Insert the records into the table variable */
INSERT INTO Your_Actual_Table_Name (
[EN_INTFC_ID],
[EN_INTFC_LINE_NUM],
[EN_BILL_SOURCE_ID],
[EN_BUSINESS_UNIT],
[EN_ASSET_NAME],
[EN_POSTING_DATE],
[EN_FISCAL_YEAR],
[EN_FISCAL_PERIOD],
[EN_CUSTOMER_ID],
[EN_DOC_TYPE],
[EN_TARGET_INVOICE],
[EN_INVOICE_DT],
[EN_REVNUE_TYPE],
[EN_QTY],
[EN_GROSS_EXT_AMT],
[EN_DESCR],
[EN_CONTRACT],
[EN_PRODUCT_TYPE],
[EN_UNIT_OF_MEASURE] )
(SELECT [EN_INTFC_ID],
[EN_INTFC_LINE_NUM],
[EN_BILL_SOURCE_ID],
[EN_BUSINESS_UNIT],
[EN_ASSET_NAME],
[EN_POSTING_DATE],
[EN_FISCAL_YEAR],
[EN_FISCAL_PERIOD],
[EN_CUSTOMER_ID],
[EN_DOC_TYPE],
[EN_TARGET_INVOICE],
[EN_INVOICE_DT],
[EN_REVNUE_TYPE],
[EN_QTY],
[EN_GROSS_EXT_AMT],
[EN_DESCR],
[EN_CONTRACT],
[EN_PRODUCT_TYPE],
[EN_UNIT_OF_MEASURE]
FROM #someTargetTable)
/* Remove the document from memory */
EXEC sp_xml_removedocument #xmlHandle
END
// your sql command below.
SqlCommand insert = new SqlCommand ("sp_InsertData '" + xmlData + "'", conn);
insert.CommandTimeout = 5000;
insert.ExecuteNonQuery();
conn.Close()
// my code and how you can utilize the using(){} statement along with code to convert a DataTable to XML then pass that xml to the stored procedure which I have depicted above
private bool ProcessSomeDataTableToXML(DataTable dataTable)
{
String xmlData = ConvertDataTableToXML(dataTable);
var ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["yourdatabase"].ConnectionString;
using (SqlConnection connection = new SqlConnection(ConnString))
{
using (SqlCommand command = new SqlCommand("sp_InsertData '" + xmlData + "'", connection))
{
connection.Open();
try
{
command.ExecuteNonQuery();
fileInserted = true;
}
catch (SqlException sqlEx)
{
fileInserted = false;
Console.WriteLine(sqlEx.Message);
}
}
}
return fileInserted;
}
private static string ConvertDataTableToXML(DataTable dtData)
{
DataSet dsData = new DataSet();
StringBuilder sbSQL;
StringWriter swSQL;
string XMLformat;
try
{
sbSQL = new StringBuilder();
swSQL = new StringWriter(sbSQL);
dsData.Merge(dtData, true, MissingSchemaAction.AddWithKey);
dsData.Tables[0].TableName = "XMLDataTable";
foreach (DataColumn col in dsData.Tables[0].Columns)
{
col.ColumnMapping = MappingType.Attribute;
}
dsData.WriteXml(swSQL, XmlWriteMode.WriteSchema);
XMLformat = sbSQL.ToString();
sbSQL = null;
swSQL = null;
return XMLformat;
}
catch (Exception sysException)
{
throw sysException;
}
}
An obvious problem is in your while condition:
ds.Tables[0].Rows.Count < ds.Tables[0].Rows.Count + 1
i.e. count < count + 1
i.e. true
Your loop is designed never to stop. You might change it to
while (jump < ds.Tables[0].Rows.Count)
1) You have an infite loop (ds.Tables[0].Rows.Count < ds.Tables[0].Rows.Count + 1)
2) Connection management: You don't need to open an close the connection on each iteration. Use a using block for disposing the connection once you are done with it.
I have a form that generate inputs dynamically, then I get their values and generate command parameters dynamically.
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd =new SqlCommand("insert_op",con);
cmd.CommandType = CommandType.StoredProcedure;
for (int i = 0; i < Request.Form.Count; i++)
{
if (Request.Form["frm_option" + (i + 1)] != null)
{
cmd.Parameters.AddWithValue("#op" + i, Request.Form["frm_option" + (i + 1)]);
}
}
try
{
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
catch
{
}
How can I pass these dynamic parameters to SQL Server stored procedure and how should stored procedure be?
First of all, this isn't the right design.
To achieve your goal you need to pass multiple values in SQL statment as follows
SQL
INSERT INTO tbl_options(op_name) VALUES (value1),(value2),...(nthValue)
Code
Your code will be something like this
string command = "INSERT INTO tbl_options(op_name) VALUES";
for (int i = 0; i < Request.Form.Count; i++)
{
if (Request.Form["frm_option" + (i + 1)] != null)
{
command += "(#op" + i + "),";
cmd.Parameters.AddWithValue("#op" + i, Request.Form["frm_option" + (i + 1)]);
}
}
If you want to "insert each parameter into separate row" then perhaps it is better to use table variable as a stored prosedure parameter?
Your User Defined Table Type and stored procedure might look like:
create type dbo.ValueTableType as table (Value varchar(255))
GO
create procedure dbo.InsertValues
#Values dbo.ValueTableType readonly
as
begin
insert into dbo.YourTable (Value)
select Value from #Values;
end
See this ADO.NET example of how to initialize and pass a table parameter to stored procedure https://stackoverflow.com/a/10409710/623190
You can provide defaults for every field in the table, so any parameters you do not pass in will get the default. Here I demonstrate defaults of NULL.
CREATE PROCEDURE [dbo].[sproc_tbl_options_Insert]
#op_name nvarchar(50) = NULL,
#op_somethingelse nvarchar(5) = NULL,
#op_number int = NULL
AS
BEGIN
INSERT INTO [tbl_options] (op_name, op_somethingelse, op_number)
VALUES (#op_name, #op_somethingelse, #op_number);
END
This is my stored procedure:
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(goals = ''',
goals,
''', round(value, 2), NULL)) AS ',
goals
)
) INTO #sql
FROM sgwebdb.dim_module;
SET #sql = CONCAT('SELECT alternative, ', #sql, ' FROM sgwebdb.dim_module GROUP BY
alternative');
prepare stmt from #sql;
execute stmt;
I need to call this procedure in below code instead of below MySQL query (query1)
C# code -->
protected void Page_Load(object sender, EventArgs e)
{
BindGrid();
}
private void BindGrid()
{
string query1 = "SELECT alternative as 'Alternative',max( case when goals='G1' then round( value, 2 ) end ) as 'Goal 1',max( case when goals='G2' then round( value, 2 ) end ) as 'Goal 2',max( case when goals='G3' then round( value, 2 ) end ) as 'Goal 3',max( case when goals='G4' then round( value, 2 ) end ) as 'Goal 4' from sgwebdb.dim_module group by alternative";
this.GridView1.DataSource = DataManager.DatabaseManager.GetOrCreateConnection(DataManager.DatabaseManager.ConnectionType.MySQL).GetData(query1);
GridView1.DataBind();
for (int n = 0; n < (GridView1.Rows.Count - 1); n++)
{
Textval.Text = GridView1.Rows[n].Cells[1].Text;
double gdval = Convert.ToDouble(Textval.Text);
}
}
Inplace of Query1 in c# code how can I call above MySQL procedure ?
When you create the MySqlCommand object you need to set the Name of the Stored Procedure in the CommandText property and set the CommandType property to CommandType.StoredProcedure.
Here's a code sample setting up a MySqlCommand object to do just that:
MySqlCommand command = new MySqlCommand();
command.Connection = connection;
command.CommandText = "NameOfYourStoredProcedure";
command.CommandType = CommandType.StoredProcedure;
A little caveat with adding parameters is that the names of the parameters in the stored procedure must match those added to the Parameters collection of the MySqlCommand object.
How to update the full row if BatchNumber (in my case) exists?
In my table batch number is unique and I need to update the entire row or the quantity column if Batchnumber is exist
Please, help me to do this in a proper way
{
var conn = new SqlConnection(GetConnectionString());
var StrBuilder = new StringBuilder(string.Empty);
var splitItems = (string[])null;
foreach (string item in SC_PurLinr)
{
const string sqlStatement = "INSERT INTO DEL_Stores (DealerCode, Code, Qty, ExpireDate, BatchNumber) VALUES";
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
StrBuilder.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3], splitItems[4]);
}
}
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(StrBuilder.ToString(), conn) { CommandType = CommandType.Text };
cmd.ExecuteNonQuery();
wucMessagePopup1.showPopup(1, string.Empty, "Record Saved Successfully.");
}
catch (SqlException ex)
{
}
finally
{
conn.Close();
}
}
Use MERGE from SQL Server 2008:
WITH new_rows (
SELECT #value value
,#BatchNumber BatchNumber)
MERGE DEL_Stores target
USING new_rows source ON source.BatchNumber = target.BatchNumber
WHEN MATCHED THEN
UPDATE SET value = #value
WHEN NOT MATCHED THEN
INSERT (
BatchNumber
,value)
VALUES(
source.BatchNumber
source.value);
You can achieve this by stored procedure in better way.
Your procedure should be like this.
create PROCEDURE usp_Namae
#parmeter INT
,#parmeter INT
,#BatchNumber INT
AS
BEGIN
IF NOT EXISTS (
SELECT *
FROM tblname
WHERE BatchNumber = #BatchNumber
)
BEGIN
--INSERT query
END
ELSE
BEGIN
--Update query
END
END
Just add IF statement before insert data as below:
IF EXISTS (select * from sys.columns where object_id = OBJECT_ID(N'DEL_Stores') and name='BatchNumber')
BEGIN
// Do insert here
END