How to create stored procedure - sql

How to create stored procedure for this c# statement
String Orders = "INSERT INTO Orders VALUES('" + DDLCustomerID.SelectedValue + "','" + Convert.ToInt32(TxtNetPrice.Text) + "');" + " SELECT SCOPE_IDENTITY();";
SqlCommand command = new SqlCommand(Orders, Connection);
command.CommandType = CommandType.Text;
Connection.Open();
int intID = Convert.ToInt32(command.ExecuteScalar());
String Orderdetails1 = "INSERT INTO OrderDetails VALUES(" + intID + ",'" + DDLProduct1.SelectedItem + "','" + Convert.ToInt32(TxtPrice1.Text) + "','" + Convert.ToInt32(TxtQuantity1.Text) + "','" + Convert.ToInt32(TxtTotalPrice1.Text) + "')";
SqlCommand Command1 = new SqlCommand(Orderdetails1, Connection);
Command1.CommandType = CommandType.Text;
Command1.ExecuteNonQuery();
String Orderdetails2 = "INSERT INTO OrderDetails VALUES(" + intID + ",'" + DDLProduct2.SelectedItem + " ','" + Convert.ToInt32(TxtPrice2.Text) + "','" + Convert.ToInt32(TxtQuantity2.Text) + "','" + Convert.ToInt32(TxtTotalPrice2.Text) + "')";
SqlCommand Command2 = new SqlCommand(Orderdetails2, Connection);
Command2.CommandType = CommandType.Text;
Command2.ExecuteNonQuery();
String Orderdetails3 = "INSERT INTO OrderDetails VALUES(" + intID + ",'" + DDLProduct3.SelectedItem + " ','" + Convert.ToInt32(TxtPrice3.Text) + "','" + Convert.ToInt32(TxtQuantity3.Text) + "','" + Convert.ToInt32(TxtTotalPrice3.Text) + "')";
SqlCommand Command3 = new SqlCommand(Orderdetails3, Connection);
Command3.CommandType = CommandType.Text;
Command3.ExecuteNonQuery();
Response.Write("<script>alert('Successfully Inserted');</script>");
Connection.Close();
How to create stored procedure for this c# statement
The table I created in SQL SERVER is
CREATE TABLE Customers
(
CustomerID INT IDENTITY(1, 1) PRIMARY KEY,
FirstName NVARCHAR(45),
LastName NVARCHAR(45),
Address NVARCHAR(45)
)
CREATE TABLE Orders
(
OrderID INT IDENTITY(1, 1) PRIMARY KEY,
CustomerID INT FOREIGN KEY REFERENCES Customers(CustomerID),
TotalPrice INT
)
CREATE TABLE OrderDetails
(
OrderID INT FOREIGN KEY REFERENCES Orders(OrderID),
ProductName NVARCHAR(45),
Quantity NVARCHAR(45),
Price NVARCHAR(45),
TotalPrice INT
)
I want to create a stored procedure for this statement

This is the SQL code that you need to write :
Syntax for stored procedure :
Create Proc Proc_Name
(
#PARAM1 DATATYPE,
....
)
AS
BEGIN
BODY OF THE SP
END
This is the way to create the stored procedure in SQL.
As you have bunch of queries that you are executing at the single shot.
You also tack care of your transaction.
If suppose your last insert query got EXCEPTION then you above all the queries needs to be rollback & not should be executed.
I have also done rollback in the stored procedure.
CREATE PROC Procedure_Name
(
#Customer_id INT,
#TxtNetPrice FLOAT,
#DDLProduct1 INT,
#TxtQuantity1 FLOAT,
#TxtTotalPrice1 FLOAT,
#TxtPrice1 FLOAT,
#intID INT
)
AS
BEGIN
SET NOCOUNT ON
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO Orders VALUES(#Customer_id,#TxtNetPrice)
DECLARE #S_ID int;
SET #S_ID = (SELECT SCOPE_IDENTITY())
INSERT INTO
OrderDetails
VALUES(#intID,#DDLProduct1,#TxtPrice1,#TxtQuantity1,#TxtTotalPrice1)
COMMIT
END TRY
BEGIN CATCH
DECLARE #ERROR_MSG NVARCHAR(MAX), #SEVERITY INT, #STATE INT
SELECT #SEVERITY = ERROR_SEVERITY(), #STATE = ERROR_STATE()
, #ERROR_MSG = ERROR_MESSAGE() + ' err src line: ' + CAST( ERROR_LINE() AS NVARCHAR(20)) + ' ' + ISNULL(ERROR_PROCEDURE(), '');
--#ERROR_MSG = ERROR_MESSAGE()
ROLLBACK;
-- RE-THROW EXCEPTION FOR DIAGNOSTIC VISIBILITY
RAISERROR (#ERROR_MSG ,#SEVERITY, #STATE);
RETURN
END CATCH
END

Related

Unclosed quotation mark after the character string ')'

I have a stored procedure SP_CHADOTHERREPORTS
When executing SP_CHADOTHERREPORTS from VB.NET. I get an error like this:
here is my code for executing SP_CHADOTHERREPORTS in VB.NET:
Dim subreporttype as varchar = "Report1"
Dim DatabaseFINAL as varchar = "TBLREPORT"
Dim acctcode as varchar = "TBLREPORT.acctcode"
Dim varmonth as integer = 1
Dim varyear as integer = 2011
Execute("EXECUTE SP_CHADOTHERREPORTS '" & subreporttype & "','" & DatabaseFINAL & "','" & acctcode & "'," & dt.Rows(ctr).Item("ReporttypeName").ToString & "," & varmonth & ", " & varyear & "")
While this one is the code in SP_CHADOTHERREPORTS from SQL SERVER 2008:
ALTER PROCEDURE [dbo].[SP_CHADOTHERREPORTS]
#Subreport as varchar(100),
#TableName as varchar(100),
#AccountCode as varchar(100),
#ReportName as varchar(100),
#AcctPeriod as numeric(18,0),
#AcctYear as numeric(18,0)
AS
IF #Subreport = 'REPORT1'
BEGIN
DECLARE #Query as varchar(1000)
SET #Query =
'UPDATE CHADotherCharges ' +
' SET Jan = ( ' +
' SELECT Jan FROM '+ #TableName +
' WHERE CHADothercharges.acctcode = '''+ #AccountCode +'' +
' AND ReportName = '+ #ReportName +
' AND acctperiod = '+ convert(varchar(18), #AcctPeriod) +
' AND acctyear = '+ convert(varchar(18), #AcctYear) +
') ' +
'FROM Chadothercharges WHERE type IN(''+'',''SUM'',''-'')'
EXEC (#Query)
END
One obvious problem is this line:
' WHERE CHADothercharges.acctcode = '''+ #AccountCode +'' +
-------------------------------------------------------^
That does nothing. I assume you want to put in a single quote, as ''''.
However, the real way to approach this is by using sp_executesql and using parameters for all the constant values in the query. You can't use this for #TableName, but you can use it for the values in the WHERE.

I can't insert a record in database: "Invalid Column Name"

create PROCEDURE [dbo].[pro_InsertRecord]
#table varchar(30) ,
#field varchar(max) ,
#value varchar(max)
AS
SET NOCOUNT ON
BEGIN
EXEC('INSERT INTO ' + #table + '(' + #field + ') VALUES ( '+ #value +')')
END
I can't insert a record in database but i receive an insert error message as "Invalid Column Name"
my code:
string fieldnames = "Login_UserName, Login_Password, Login_Role_Id";
string fieldvalues = UserName +"','" + Password + "'," + Role ;
com.Common.InsertRecord("Login", fieldnames, fieldvalues);
Instead of
string fieldvalues = UserName +"','" + Password + "'," + Role ;
use
string fieldvalues = "'" + UserName + "','" + Password + "'," + Role ;

using Transaction query in jsp page

I use below query in my jsp page. but I'm not sure Is it true to use this query in jsp page.
int i = st.executeUpdate("'BEGIN TRANSACTION DECLARE #id [int] SELECT #id = SCOPE_IDENTITY() INSERT INTO Viewer(Reserve_ID, F_Name, L_Name, Competition_ID, City, Phone, [E-mail]) VALUES (#id, '" + fname + "','" + lname + "','" + 30 + "','" + city + "','" + phone + "','" + email + "' ) INSERT INTO Reservation_Inf(Reservation_Date, Competition_ID, NumberOfTicket, Position_ID) VALUES ('" + dNow + "','" + 30 + "','" + 1 + "','" + 8 + "' ) COMMIT TRANSACTION '" );
if (i > 0) {
response.sendRedirect("Success.jsp");
} else {
response.sendRedirect("Fail.jsp");
}
It gives this error :
Incorrect syntax near 'BEGIN TRANSACTION DECLARE #id [int] SELECT #id = SCOPE_IDENTITY() INSERT INTO Viewer(Reserve_ID, F_Name, L_Name, Competition_ID,'.

How to read the values in SQL

I am tying to read the values in SQl.
I am creating one purchase order If suppose any body has updated the price for the inventory then I am first checking that price is available or not.
If that price is not available then I am First Inserting that price into the datbase & then map new price with the inventory.
I have already achieved this functionality but I have wrote five inline query for this now i need to
change the code & replace with the single stored procedure. & how I can write the logic into the SQL
Here is my code with the explanation
//Checking that Buying Price Is Exist or not
//string CheckingIBM = "select * from RS_Inventory_Buying_Master where buying_price ='" + UpdatedPrice + "'";
//cm.TableConnect(CheckingIBM);
//If Buying Price is Exist then Update PIIM table with new buying_product_id
if (cmIS_Price_Exist.rs.Read())
{
//If Buying Price is Exist then Update PIIM table with new buying_product_id
common cm1 = new common();
string BuyingProductId = cmIS_Price_Exist.rs["buying_product_id"].ToString();
string UpdatePIIM = "update RS_Purchase_Invoice_Info_Master set buying_product_id = '" + BuyingProductId + "', qty = '" + UpdatedQuantity + "',tax_id ='" + TaxDetails + "',picreated = 1 where purchase_order_no = '" + PO + "' and product_id = '" + ProductId + "'";
cm1.TableInsert(UpdatePIIM);
cm1.con.Close();
}
//If Buying Price does not Exist then first Insert the price & then Update the other tables
else
{
//If Price is not exist then firsrt insert the price
common cm2 = new common();
string InsertBuyingPrice = "insert into RS_Inventory_Buying_Master (buying_price,latest) values ('" + UpdatedPrice + "','0')";
cm2.TableInsert(InsertBuyingPrice);
cm2.con.Close();
//After inserting the price find the buying product Id of that price
common cm3 = new common();
string FindingUpdatedPrice = "select * from RS_Inventory_Buying_Master where buying_price ='" + UpdatedPrice + "'";
cm3.TableConnect(FindingUpdatedPrice);
//Now finallly after finding the buying price id by using the inserted Price. Now update the buying product id of PIIM
if (cm3.rs.Read())
{
string BuyingProductId = cm3.rs["buying_product_id"].ToString();
//Now finallly after finding the buying price id. Now update the buying product id of PIIM
common cm4 = new common();
string UpdatePIIM = "update RS_Purchase_Invoice_Info_Master set buying_product_id = '" + BuyingProductId + "', qty = '" + UpdatedQuantity + "',tax_id ='" + TaxDetails + "',picreated = 1 where purchase_order_no = '" + PO + "' and product_id = '" + ProductId + "'";
cm4.TableInsert(UpdatePIIM);
cm4.con.Close();
}
cm3.con.Close();
}
Any suggesion will be appreciated.
declare #BuyingProductId varchar(50)
set #BuyingProductId = (select isnull(buying_product_id, '') from RS_Inventory_Buying_Master where buying_price = #UpdatedPrice)
if(#BuyingProductId <> '')
begin
--your update query
update RS_Purchase_Invoice_Info_Master set buying_product_id = #BuyingProductId ,
qty = #UpdatedQuantity ,tax_id = #TaxDetails ,picreated = 1
where purchase_order_no = #PO
and product_id = #ProductId ;
end
else
begin
--your insert query
insert into RS_Inventory_Buying_Master (buying_price,latest)
values (#UpdatedPrice,'0')
set #BuyingProductId = (SELECT ##IDENTITY)
update RS_Purchase_Invoice_Info_Master set buying_product_id = #BuyingProductId ,
qty = #UpdatedQuantity ,tax_id = #TaxDetails ,picreated = 1
where purchase_order_no = #PO
and product_id = #ProductId ;
end
Check with this query. Please make sure to create new sp and provide all the value like #UpdatedQuantity etc.

Is this UPDATE table statement correct in an msdn topic

I have seen this type of UPDATE statement (just like insert statement) in the following msdn topic:
http://msdn.microsoft.com/en-us/library/aa0416cz.aspx#Y2461
UPDATE statement:-
adapter.UpdateCommand = New SqlCommand("UPDATE Customers " &
"(CustomerID, CompanyName) VALUES(#CustomerID, #CompanyName) " & _
"WHERE CustomerID = #oldCustomerID AND CompanyName = " &
"#oldCompanyName", connection)
Is this statement correct or not?
I have tried executing it and it is giving syntax errors.
No, it should be:
UPDATE Customers
SET
CustomerID = #CustomerID,
CompanyName = #CompanyName
WHERE
CustomerID = #oldCustomerID AND
CompanyName = #oldCompanyName
Or to be complete with your sample code, it should be:
adapter.UpdateCommand = New SqlCommand("UPDATE Customers SET CustomerID = #CustomerID, CompanyName = #CompanyName WHERE CustomerID = #oldCustomerID AND CompanyName = #oldCompanyName", connection)
Here is another reference for you and this situation: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.updatecommand.aspx
That SQL appears to be correct for an INSERT INTO but not for an UPDATE It should read:
adapter.UpdateCommand = New SqlCommand("UPDATE Customers" & _
" SET CustomerID = #CustomerID, CompanyName = #CompanyName)" & _
" WHERE CustomerID = #oldCustomerID AND CompanyName =" & _
" #oldCompanyName", connection)
That SQL is what one would call paramaterized, so that makes this code (lower in the snippet) very important:
adapter.UpdateCommand.Parameters.Add( _
"#CustomerID", SqlDbType.NChar, 5, "CustomerID")
adapter.UpdateCommand.Parameters.Add( _
"#CompanyName", SqlDbType.NVarChar, 30, "CompanyName")
' Pass the original values to the WHERE clause parameters.
Dim parameter As SqlParameter = dataSet.UpdateCommand.Parameters.Add( _
"#oldCustomerID", SqlDbType.NChar, 5, "CustomerID")
parameter.SourceVersion = DataRowVersion.Original
parameter = adapter.UpdateCommand.Parameters.Add( _
"#oldCompanyName", SqlDbType.NVarChar, 30, "CompanyName")
parameter.SourceVersion = DataRowVersion.Original
As far as I can see the syntax is not valid. The following gives Incorrect syntax near '('.
I suggest changing it as per Dan's answer.
CREATE TABLE Customers
(
CustomerID INT,
CompanyName VARCHAR(10)
)
DECLARE
#CustomerID INT,
#CompanyName VARCHAR(10),
#oldCustomerID INT,
#oldCompanyName VARCHAR(10)
UPDATE Customers (CustomerID, CompanyName)
VALUES(#CustomerID, #CompanyName)
WHERE CustomerID = #oldCustomerID AND CompanyName = #oldCompanyName