Is this UPDATE table statement correct in an msdn topic - sql

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

Related

How to solve this error of conversion failed?

I am getting this error
Conversion failed when converting the varchar value 'Thowheed' to data type int.
I visited and checked in stack overflow, but I couldn't find answer
I added values in drop down list, once I select and click ok button it has to show me the record from database.
This is my code
string cs = ConfigurationManager.ConnectionStrings["Nibrass_DBConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT Date as Date,Credit, Debit_From as Received_From, Credit_Amount as amount, Reason From Transaction_Credit where Credit = " + DropDownListSelectAccount.SelectedValue+ " or cast(Debit_From as varchar) = " + DropDownListSelectAccount.SelectedValue + " ORDER BY Date DESC";
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
while(rd.Read())
{
DateTime dt = Convert.ToDateTime(rd[0]);
string receivedFrom = rd[1].ToString();
int amount = Convert.ToInt32(rd[2]);
}
con.Close();
}
My database table definition is
CREATE TABLE [dbo].[Transaction_Credit]
(
[Date] DATE NOT NULL,
[Credit] VARCHAR (50) NOT NULL,
[Debit_From] VARCHAR (50) NOT NULL,
[Reason] VARCHAR (100) NULL,
[Credit_Amount] INT NOT NULL,
[Balance] INT NULL
);
You should not be concatenating your string. This is a bad practice and your code becomes vulnerable to SQL Injection.
You should use parameters instead:
cmd.CommandText = #"
SELECT Date
, Credit
, Debit_From AS Received_From
, Credit_Amount AS Amount
, Reason
FROM Transaction_Credit
WHERE Credit = #DropDownListSelectAccount
OR Debit_From = #DropDownListSelectAccount
ORDER BY Date DESC";
cmd.Parameters.Add("#DropDownListSelectAccount", SqlDbType.VarChar, 50). Value) = DropDownListSelectAccount.SelectedValue;
By the way, you don't need to cast Debit_From as a varchar, since it's already like that in your database.
This is your query:
select Date as Date, Credit, Debit_From as Received_From,
Credit_Amount as amount, Reason
from Transaction_Credit
where Credit = " + DropDownListSelectAccount.SelectedValue+ " or
cast(Debit_From as varchar) = " + DropDownListSelectAccount.SelectedValue + "
order by Date DESC;
The code reading this is:
int amount = Convert.ToInt32(rd[2]);
But the 3rd column is Received_From, not amount. That is probably your problem.
Also, cast(Debit_From as varchar) is very dangerous. When you don't include a length for varchar(), SQL Server inserts a length depending on the context. Just don't do a conversion where you don't need one.

How to create stored procedure

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

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.

get return value from stored procedure without output parameter

I have a vb.net application that inserts records into a db table using a stored procedure that is supposed to return a value. This stored procedure was setup by someone else and initially was linked to a webservice through which my application made the insert and got the return value in the returned xml. I now have access to the db table and not sure how to receive the return value in my vb.net method.
SQl stored procedure snippet;
#urlname varchar(500),
#siteid varchar(16),
#origin varchar(50),
#queryid varchar(25)
AS
SET NOCOUNT ON;
declare #cnt int
declare #serverip varchar(16)
declare #mincnt int
declare #siteservercnt int
select #cnt=COUNT(*) from sites
where urlname=#urlname
if #cnt = 0
begin
insert into sites (urlname,siteid,exported,origin,queryid)
values(#urlname,#siteid,1,#origin,#queryid)
select #siteservercnt = COUNT(*) from siteserverip where siteid=#siteid
if #siteservercnt=0
begin
select top 1 #mincnt=COUNT(*),#serverip=serverip from siteserverip
group by serverip
order by COUNT(*)
select top 1 #mincnt=sitecount,
#serverip=serverip from serveripcounts
order by sitecount
insert into siteserverip values(#siteid,#serverip)
update serveripcounts set sitecount=sitecount+1
where serverip=#serverip
end
end
SELECT siteid from sites
where urlname=#urlname
return
and my vb.net code to do the insert
CommandObj.CommandText = "Getsite"
CommandObj.CommandTimeout = 90
Dim newUrl As String = String.Empty
CommandObj.Parameters.Clear()
Dim m_param As SqlParameter
m_param = CommandObj.Parameters.Add("#urlname", SqlDbType.VarChar, 500)
m_param.Direction = ParameterDirection.Input
m_param.Value = name
m_param = CommandObj.Parameters.Add("#siteid", SqlDbType.VarChar, 16)
m_param.Direction = ParameterDirection.Input
m_param.Value = siteid
m_param = CommandObj.Parameters.Add("#origin", SqlDbType.VarChar, 50)
m_param.Direction = ParameterDirection.Input
m_param.Value = method
m_param = CommandObj.Parameters.Add("#queryId", SqlDbType.VarChar, 25)
m_param.Direction = ParameterDirection.Input
m_param.Value = forumID
Dim recordsAffected As Integer = CommandObj.ExecuteNonQuery
You can use ExecuteScalar to get that value. ExecuteNonQuery returns number of rows affected while you want to get the value generated by last select. You could use ExecuteReader as well but that is useful when your SP might be returning more columns and/or more rows.
'Populate first column and first row value in siteID
Dim siteID As Integer = CommandObj.ExecuteScalar

Executing SQL powershell query in VBscript

I am executing sql query in vbscript, query is as follow it gives information about drives available for each server
VBScript code (slightly restructured):
Strquery = "DECLARE #Totaldbspacegb BIGINT;" & _
"DECLARE #Totaldriveusedspacegb INT;" & _
"DECLARE #Totaldrivefreespacegb INT;" & _
"DECLARE #Svrname VARCHAR(255);" & _
"DECLARE #Sql VARCHAR(400);" & _
"DECLARE #Forcast6monthsgb NUMERIC(38, 6);" & _
"DECLARE #Forcast12monthsgb NUMERIC(38, 6);"
Strquery = Strquery & "; DECLARE #Avggrowthingb NUMERIC(38, 6);" & _
"CREATE TABLE #Temp1(Yer INT NULL, Mnth INT NULL," & _
"Sumdbinmb NUMERIC(38, 6)NULL, Id INT IDENTITY(1, 1) NOT NULL);" & _
"CREATE TABLE #Temp4(Totaldriveusedspacegb INT, Totaldrivefreespacegb INT);"
Strquery = Strquery & "; SELECT #Totaldbspacegb = SUM(Size) FROM Sys.Master_Files"
Strquery = Strquery & "; SELECT #Totaldbspacegb = #Totaldbspacegb * 8. / 1024.0 / 1024"
Strquery = Strquery & "; SET #Svrname = '" & Strserver & "';"
Sql = " Powershell.Exe - C ""Get-WmiObject -Class Win32_Volume -Filter ''DriveType = 3''| select name,label,capacity,freespace | foreach{$_.name+''!''+$_.label+''|''+$_.capacity/1048576+''%''+$_.freespace/1048576+''*''}"""
Strquery = Strquery & "CREATE TABLE #Output(Line VARCHAR(255)); INSERT INTO #Output"
Strquery = Strquery & "; EXEC Xp_Cmdshell '" & sql & "';"
Strquery = Strquery & "; SELECT * FROM #Output;"
Resulting (formatted) SQL code:
DECLARE #Totaldbspacegb BIGINT;
DECLARE #Totaldriveusedspacegb INT;
DECLARE #Totaldrivefreespacegb INT;
DECLARE #Svrname VARCHAR(255);
DECLARE #Sql VARCHAR(400);
DECLARE #Forcast6monthsgb NUMERIC(38, 6);
DECLARE #Forcast12monthsgb NUMERIC(38, 6);
;
DECLARE #Avggrowthingb NUMERIC(38, 6);
CREATE TABLE #Temp1(Yer INT NULL,
Mnth INT NULL,
Sumdbinmb NUMERIC(38, 6)NULL,
Id INT IDENTITY(1, 1) NOT NULL
);
CREATE TABLE #Temp4(Totaldriveusedspacegb INT,
Totaldrivefreespacegb INT
);
;
SELECT #Totaldbspacegb = SUM(Size)
FROM Sys.Master_Files;
SELECT #Totaldbspacegb = #Totaldbspacegb * 8. / 1024.0 / 1024;
SET #Svrname = '...';
CREATE TABLE #Output(Line VARCHAR(255));
INSERT INTO #Output;
EXEC Xp_Cmdshell 'Powershell.Exe - C "Get-WmiObject -Class Win32_Volume -Filter ''DriveType = 3''| select name,label,capacity,freespace | foreach{$_.name+''!''+$_.label+''|''+$_.capacity/1048576+''%''+$_.freespace/1048576+''*''}"';
;
SELECT *
FROM #Output;
I am executing this query it gave me output while running from management studio while running in .vbs file it give me record count as null, how to find whether query is executing sucessfully.
is it due to powershell command it is not running in vbscript.
Please help
Do you want to update the temporary table #Output with the result of the PowerShell command? If so, I don't think your instructions will do what you want.
INSERT INTO #Output;
EXEC Xp_Cmdshell 'Powershell.Exe -C "..."';
SELECT *
FROM #Output;
INSERT INTO #Output; is not a valid statement, and you don't do anything with the output of the PowerShell command.