C# pass parameters to Postgres Npgsqlcommand DO block - c#

I get the error "42883: operator does not exist: integer =# integer" Npgsql.PostgresException
when trying to pass parameters to a DO block:
var cmd = new NpgsqlCommand();
cmd.CommandText =
#"DO $$
BEGIN
IF EXISTS (SELECT id FROM pub.table1 WHERE id = #id) THEN
UPDATE pub.table1
SET Field1 = #Field1
,Field2 = #Field2
WHERE id = #id;
ELSE
INSERT INTO pub.table1 (id, Field1, Field2)
VALUES (#id, #Field1, #Field2);
END IF;
END $$;";
cmd.Parameters.AddWithValue("#id", 1);
cmd.Parameters.AddWithValue("#Field1", "text");
cmd.Parameters.AddWithValue("#Field2", "text2");
Otherwise connection to postgres works and also (classic) queries work when passing parameters; e.g.:
cmd.CommandText = #"SELECT * FROM pub.table1 WHERE id = #id;";
Is it not possible to pass parameters to a "DO" block or am I missing something?
Thank you.
M

Related

Web API to call a stored procedure to insert/update DB

I have been working on creating the Web API that accepts the input parameter and calls a Stored Procedure passing the input parameter we received that insert/updates the Account Table in the Database. Now that is perfectly , but my API also need to select the record which was updated/inserted and return them as response
public class ProjectNameCreationController : ApiController
{
[HttpGet]
public HttpResponseMessage Get(string Account)
{
if (string.IsNullOrEmpty(Account))
{
return Request.CreateResponse(new { error = "Input parameters cannot be Empty or NULL" });
}
string strcon = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection DbConnection = new SqlConnection(strcon);
DbConnection.Open();
SqlCommand command = new SqlCommand("[dbo].[usp_InserUpadte]", DbConnection);
command.CommandType = CommandType.StoredProcedure;
//create type table
DataTable table = new DataTable();
table.Columns.Add("AccountID", typeof(string));
table.Rows.Add(Account);
SqlParameter parameter = command.Parameters.AddWithValue("#account_TT", table);
parameter.SqlDbType = SqlDbType.Structured;
parameter.TypeName = "account_TT";
command.ExecuteNonQuery();
Now I am not sure if we will able to select the record that was now insert/updated as part of the Stored Procedure or will I have to create a Query seperately like below
string strQuery = "select AccountID,CounterSeq from Account where AccountID = #accountID ";
var cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#accountID",Account);
Because I will have to Return the response as AccountID-CounterSeq (Eg: IT-1) when the API is called like http://localhost/api/ProjectNameCreation?Account=IT. How can I deal with this. Any help is greatly appreciated
You have to change your procedure as below it will return a record of last inserted or updated.
**--for insert**
IF #StatementType = 'Insert'
BEGIN
insert into Account (first_name,last_name,salary,city) values( #first_name, #last_name, #salary, #city)
--below line to return last inserted record
select * from Account where accountid= SCOPE_IDENTITY()
END
**--for Update**
IF #StatementType = 'Update'
BEGIN
UPDATE Account SET
First_name = #first_name, last_name = #last_name, salary = #salary,
city = #city
WHERE accountid= #accountid
--below line to return last Updated record
select * from account where accountid = #accountid

MySQL query not works (C#)

I try to update my MYSQL table with this code.
string sqlquery = String.Format("if exists(select 1 from orders where id =\" {0}\" ) begin update orders set customer_id = \"{1}\", total = \"{2}\", fio = \"{3}\", adress =\" {4}\" where id = \"{0}\" end else begin insert into orders (id, customer_id, total, fio, adress) values(\"{0}\", \"{1}\", \"{2}\", \"{3}\", \"{4}\") end", id, customer_id, total, fio, adress);
MySqlCommand addCommand2 = new MySqlCommand(sqlquery.ToString(), connection);
addCommand2.ExecuteNonQuery();
But I have this error
Additional information: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'if exists(select 1 from orders where id = 1913 ) begin update orders set custome' at line 1
Database
What wrong in query?
Thank's for help!
why dont you do it in more elegant way:Something like.:
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "if exists(select 1 from orders where id =#id)
begin
update orders set customer_id = #customer_id, total = #total, fio = #fio, adress =#adress where id = #id end
else
begin insert into orders (id, customer_id, total, fio, adress) values(#id, #customer_id, #total, #fio,#adress) end";
command.Parameters.AddWithValue("#id", val1);
command.Parameters.AddWithValue("#customer_id", val2);
command.Parameters.AddWithValue("#total", val3);
command.Parameters.AddWithValue("#fio", val4);
command.Parameters.AddWithValue("#adress", val5);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}

Two ExecuteScalar then query

I'm looking for a way to check if a customer ID exists in the Customer table, and if it exists in the table being queried.
If it doesn't exist in the Customer table or it already exists in the table being queried (or it is in Customer but also already exists in table in question) then I don't want it to insert the data.
I thought that maybe I could do if..if code - more code - if..if code - else, but that didn't work. Here is what I mean:
cmd.CommandText = "SELECT COUNT(*) FROM Customer WHERE customer_id = #cid";
cmd.Connection = conn;
conn.Open();
int count = (int)cmd.ExecuteScalar();
conn.Close();
if (count < 1)
{
System.Web.HttpContext.Current.Response.Write("<script>alert('Customer ID does not exist and will not be submitted')</script>");
tb0.Focus();
}
cmd.CommandText = "SELECT COUNT(*) FROM table_name WHERE customer_id = #cid";
cmd.Connection = conn;
conn.Open();
int count2 = (int)cmd.ExecuteScalar();
conn.Close();
if(count2 > 0)
{
System.Web.HttpContext.Current.Response.Write("<script>alert('Customer ID already exists in table_name and will not be submitted')</script>");
tb0.Focus();
}
else
{
cmd.CommandText = "INSERT INTO table_name VALUES(#cid, #val1, #val2, #val3, #val4, #val5)";
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close(); }
Unless I comment one out then the second one will work and the first I guess gets ignored? I'm not really sure but they both work if the other is commented out
Errors from answer:
Incorrect syntax near the keyword 'THEN'.
Incorrect syntax near the keyword 'ELSE'.
Incorrect syntax near the keyword 'THEN'.
Incorrect syntax near the keyword 'ELSE'.
#"IF NOT EXISTS (SELECT * FROM Customer WHERE customer_id = #cid) THEN BEGIN
SELECT 'NO_CUSTOMER' as Result
END ELSE IF EXISTS (SELECT * FROM table_name WHERE customer_id = #cid) THEN BEGIN
SELECT 'ALREADY_RECORD' as Result
END ELSE BEGIN
INSERT INTO table_name VALUES(#cid, #val1, #val2, #val3, #val4, #val5);
SELECT 'SUCCESS' AS Result;
END";
Why not try something a bit simpler, like this?
cmd = conn.CreateCommand();
cmd.CommandText =
#"IF NOT EXISTS (SELECT * FROM Customer WHERE customer_id = #cid) THEN BEGIN
SELECT 'NO_CUSTOMER' as Result
END ELSE IF EXISTS (SELECT * FROM table_name WHERE customer_id = #cid) THEN BEGIN
SELECT 'ALREADY_RECORD' as Result
END ELSE BEGIN
INSERT INTO table_name VALUES(#cid, #val1, #val2, #val3, #val4, #val5);
SELECT 'SUCCESS' AS Result;
END";
cmd.Parameters.AddWithValue(#cid, ...);
cmd.Parameters.AddWithValue(#val1, ...);
cmd.Parameters.AddWithValue(#val2, ...);
...
switch((string)cmd.ExecuteScalar()) {
case "NO_CUSTOMER":
System.Web.HttpContext.Current.Response.Write("<script>alert('Customer ID does not exist and will not be submitted')</script>");
tb0.Focus();
break;
case "ALREADY_RECORD":
System.Web.HttpContext.Current.Response.Write("<script>alert('Customer ID already exists in table_name and will not be submitted')</script>");
tb0.Focus();
break;
}

how to pass ref variable to a SQL stored Procedure using ADO.NET?

i have that code using LINQ to call a stored procedure to save some data into database then return two variables from the stored procedure.
[ASP.NET code]
dbDataContext dbo = new dbDataContext();
dbo.AddNewDoctor(doctorName, email, password, ref DocId, ref result);
[SQL]
create PROCEDURE [dbo].[AddNewDoctor]
#doctorname nvarchar(100),
#email nvarchar(100),
#password nvarchar(MAX),
#docId int out,
#Result int out
AS
BEGIN
SET NOCOUNT ON;
declare #idCounter int
select #idCounter = count(*) from dbo.doctors
if EXISTS (select * from dbo.doctors where e_mail = #email)
begin
SET #Result = -1
set #docId= 0
end
else
begin
INSERT INTO [dbo].[doctors]
([doctor_id]
,[doctorname]
,[e_mail]
,[password]
VALUES
((#idCounter +1)
,#docotorname
,#email
,#password
)
SET #Result = 1
set #docId= (#idCounter + 1)
end
END
this code work very well what i want to do now to use ADO instead of LINQ, the problem with me is that i can't pass the ref variable as in LINQ so how can i do it using ADO
You'll have to do something like this. Use ParameterDirection
SqlParameter output = new SqlParameter(paramName, dbType);
output.Direction = ParameterDirection.Output;
command.Parameters.Add(output);
In your case you've to use SqlDbType.Int. Use Value property to read return value.
SqlParameter output = new SqlParameter(paramName, SqlDbType.Int);
output.Direction = ParameterDirection.Output;
command.Parameters.Add(output);
int Result = (int) output.Value; or int? Result = (int?) output.Value;
Try this
using (SqlConnection con = new SqlConnection("Your connection string"))
{
con.Open();
SqlCommand mycommand = new SqlCommand();
mycommand.Connection = con;
mycommand.CommandText = "dbo.AddNewDoctor";
mycommand.CommandType = CommandType.StoredProcedure;
mycommand.Parameters.AddWithValue(doctorName);
mycommand.Parameters.AddWithValue(email);
mycommand.Parameters.AddWithValue(password);
mycommand.Parameters.AddWithValue(ref DocId);
mycommand.Parameters.AddWithValue(ref result);
mycommand.ExecuteNonQuery();
}
Hope this helps thanks.
Refer to this article, there is an working example:
http://csharp-guide.blogspot.de/2012/05/linq-to-sql-call-stored-procedure-with_25.html

C# SQL stored procedure (which inserts) - pass parameters and retrieve parameter

I have a stored procedure on my server that inserts some parameters and returns the ID that was inserted. I am writing a form to do this easily but I cannot seem to get the parameter which is passed back.
To save you doing a whole bunch of possibly pointless reading, it's probably better to just pay attention to my C# code and let me know what I need to do in order to pass parameters and get one in return.
C# Default.aspx
connection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionInfo"]);
sql = "aStoredProc";
command = new SqlCommand(sql, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameter.Add(new SqlParameter("#FirstName", SqlDbType.VarChar)).Value = sFirstname;
command.Parameter.Add(new SqlParameter("#SurName", SqlDbType.VarChar)).Value = sSurname;
connection.Open();
int ID = command.ExecuteNonQuery();
connection.Close();
SQL aStoredProc
IF EXISTS(SELECT * FROM aTable WHERE ID = #ID)
-- User exists, update details
BEGIN
BEGIN TRAN
UPDATE aTable
SET
FirstName = #FirstName,
SurName = #SurName,
LastUpdate = GetDate()
WHERE ID = #ID
IF (##Error != 0)
ROLLBACK TRAN
ELSE
COMMIT TRAN
END
ELSE
-- New user
BEGIN
BEGIN TRAN
INSERT aTable (
FirstName,
SurName,
GetDate()
)
VALUES (
#FirstName,
#SurName,
#LastUpdate
)
SELECT #ID = ##IDENTITY
IF (##Error != 0)
ROLLBACK TRAN
ELSE
COMMIT TRAN
END
The parameter #ID is listed in the stored proc as:
#ID (int, Input/Output, No default)
and proc has 'Return integer'. This used to work fine with a VBA solution prior to a SQL Server 2005 upgrade.
Thanks in advance.
connection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionInfo"]);
sql = "aStoredProc";
command = new SqlCommand(sql, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameter.Add(new SqlParameter("#FirstName", SqlDbType.VarChar)).Value = sFirstname;
command.Parameter.Add(new SqlParameter("#SurName", SqlDbType.VarChar)).Value = sSurname;
command.Parameter.Add(new SqlParameter("#SurName", SqlDbType.VarChar)).Value = sSurname;
SqlParameter ParamId = cmd.Parameters.Add( "#Id", SqlDbType.Int);
ParamId.Direction = ParameterDirection.InputOutput;
command.Parameter.Add(ParamId);
connection.Open();
command.ExecuteNonQuery();
int ID = ParamId.Value;
connection.Close();
you have to add output paramter in Parameter collection.
Read Value like above.
You have an error in your SQL, it should look like this:
INSERT aTable (FirstName,SurName,LastUpdate)
VALUES (#FirstName, #SurName, GetDate() )
Not like this:
INSERT aTable (
FirstName,
SurName,
GetDate()
)
VALUES (
#FirstName,
#SurName,
#LastUpdate
)

Categories

Resources