c# how to get printout info from sql server query - c#

DECLARE #message VARCHAR(10)
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'{0}')
BEGIN
SET #message = '{1}'
END
ELSE
BEGIN
SET #message = 'NOT_OK'
END
PRINT(#message)
I execute above command from c# app.
How can I get print message?
Im trying like this:
if(connection.State.ToString() == "Closed")
{
connection.Open();
}
SqlCommand newCmd = connection.CreateCommand();
newCmd.Connection = connection;
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = string.Format(queriesMgr.getQuery(SqlQueriesID.IS_TABLE_EXISTS), "student", "OK");
SqlDataReader reader = newCmd.ExecuteReader();
if (reader.Read())
{
//not enter here(no data to read)
}
Anyone could tell me what Im doing wrong?

If you use the following query your reader will see the output select.
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'{0}')
BEGIN
SELECT '{1}'
END
ELSE
BEGIN
SELECT 'NOT_OK'
END

Related

Executescalar receives wrong value when stored procedure returns value

I am trying to return a single value to c# using the executescalar method.
When I execute the below stored procedure in SQL Server, the if..blocks are working fine but executescalar in c# always returns 0.
Please refer to the below code:
USE [xx]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[prcAddress]
#ID int,
#Name varchar(50),
#Designation varchar(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #count as Integer -- To count records
Declare #Result int -- To return result
SELECT #Result=0
SELECT #count = (SELECT count(*) FROM dbo.Address)
IF #ID >0
BEGIN
--Update the current entry
SELECT #Result=1
END
ELSE IF #ID =0 AND #count=0
BEGIN
-----do something
SELECT #Result=2
END
ELSE IF #ID=0 AND #count>0
BEGIN
----do something
SELECT #Result=3
END
ELSE
BEGIN
SELECT #Result=4
END
SELECT #Result As Result
END
GO
SqlConnection sqlCon = new SqlConnection(ConnectionString);
SqlCommand sqlCom = new SqlCommand();
try
{
sqlCom = new SqlCommand("prcAddress", sqlCon);
sqlCom.CommandType = CommandType.StoredProcedure;
sqlCom.CommandTimeout = 15;
sqlCom.Connection = sqlCon;
foreach (KeyValuePair<Object, Object> parmater in parameters)
{
if (parmater.GetType() == typeof(DateTime))
{
sqlCom.Parameters.Add("#" + parmater.Key, SqlDbType.DateTime).Value = parmater.Value;
}
else
{
sqlCom.Parameters.AddWithValue("#" + parmater.Key, parmater.Value);
}
}
if (sqlCon.State != ConnectionState.Closed)
{
sqlCon.Close();
}
sqlCon.Open();
if (sqlCom.ExecuteScalar() != null)
{
result = sqlCom.ExecuteScalar().ToString();
}
else
{
result = "";
}
}
catch (SqlException sqlEx)
{
System.Web.HttpContext.Current.Response.Redirect("~/Error.aspx", false);
}
finally
{
sqlCon.Close();
sqlCom = null;
}
You're probably seeing the result of the first select, 'SELECT #Result=0'. Either comment out all the selects prior to the last select in your stored procedure or change it to a scalar function that returns the result.

Changing Password using if and else block

I am the admin who wants to change the password for anyone by entering their email address and the new password in textbox.The stored procedure is as below:
Alter proc spChangePassword
#Email varchar(100),
#Passwordd varchar(100)
as
begin
IF EXISTS (SELECT * FROM tblRegister WHERE Email=#Email)
begin
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
Select 0
end
ELSE
BEGIN
Select -1
end
end
and the code-behind is as below:
private void ChangePassword()
{
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spChangePassword", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email",txtEmail.Text);
cmd.Parameters.AddWithValue("#Passwordd", txtPassword.Text);
cmd.ExecuteNonQuery();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
ChangePassword();
}
But i want to check if the email exists in the table using if and else statements.If the email exists then change password else throw an exception.What can i do?
You could simply change a bit the code of your procedure and have it to return a value.
0 would mean that the password updated and -1 that there is not an email like the one provided.
ALTER proc spChangePassword
#Email varchar(100),
#Passwordd varchar(100)
AS
BEGIN
IF EXISTS (SELECT * FROM Users WHERE Email=#Email) THEN
BEGIN
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
SELECT 0 AS Result
END
ELSE
BEGIN
SELECT -1 AS Result
END
END
Then you have to read the result of the stored procedure and act correspondingly. So your server side code must be changed to the following:
var reader = cmd.ExecuteReader();
while (reader.Read())
{
if(int.Parse(reader["Result"].ToString())==0)
{
// success
}
else
{
// failure
}
};
update In the if statement, you could also use this one:
Convert.ToInt32(reader["Result"])==0
I think it will work like a charm.
Inside your Stored procedure add this
Begin
DECLARE #id AS INT
SELECT #id = tblRegisterId FROM tblRegisterWHERE Email =#Email
IF #id IS not NULL
Begin
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
Select 1
End
Else
Begin
Select 0
End
End
Try this :-
private bool ChangePassword()
{
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spChangePassword", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email",txtEmail.Text);
cmd.Parameters.AddWithValue("#Passwordd", txtPassword.Text);
int count = cmd.ExecuteNonQuery();
if (count > 0)
return true;
else
return false;
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
bool success = ChangePassword(); //Use this success variable to show a message.
}
You can also change your stored procedure, but it wont throw any exception, only it will check. If the Email exists, it will execute the update query :-
Create proc spChangePassword
#Email varchar(100),
#Passwordd varchar(100)
as
begin
IF EXISTS ( SELECT * FROM tblRegister WHERE Email = #Email)
BEGIN
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
END
end
SQL
Create proc spChangePassword
#Email varchar(100),
#Passwordd varchar(100)
as
begin
IF EXISTS ( SELECT * FROM tblRegister WHERE Email = #Email)
BEGIN
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
END
ELSE
BEGIN
RAISEERROR('Email does not exists',0,1)
END
end
c#
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
{
try{
con.Open();
SqlCommand cmd = new SqlCommand("spChangePassword", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email",txtEmail.Text);
cmd.Parameters.AddWithValue("#Passwordd", txtPassword.Text);
cmd.ExecuteNonQuery();
}
catch(SqlException ee)
{
...
}
}
Try this Store Procedure ( Please use IF EXISTS)
CREATE PROCEDURE InsertName
(
#Email varchar(25),
#Passwordd varchar(25)
)
AS
IF EXISTS(SELECT 'True' FROM tblRegister WHERE Email = #Email)
BEGIN
--This means it exists,update
UPDATE tblRegister
SET Passwordd=#Passwordd where Email=#Email
SELECT 'Changed successfully'
END
ELSE
BEGIN
--This means the record isn't in there already
SELECT 'Does Not Exist'
END
private string ChangePassword()
{
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using(SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spChangePassword", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Email",txtEmail.Text);
cmd.Parameters.AddWithValue("#Passwordd", txtPassword.Text);
return cmd.ExecuteNonQuery().ToString();
}
}

Passing comma delimited parameter to stored procedure in SQL

If I pass call my stored procedure from T-SQL:
exec [dbo].[StoredProcedureName] '''Vijay'', ''Rana'', 1, 0'
in SQL Server Mgmt Studio, it works fine but when I call it from my application it gives me error
Unclosed quotation mark after the character string ''Vijay','Rana',1,0'.
I searched on the google and find this EXEC sp_executesql #FinalQuery but its not working for me
EDIT
I am calling it like
public virtual IDataReader ImportFirefighter(String query)
{
Database database = DatabaseFactory.CreateDatabase();
DbCommand command = database.GetStoredProcCommand("[StoreProcedureName]");
database.AddInParameter(command, "#query", DbType.String, query);
IDataReader reader = null;
try
{
reader = database.ExecuteReader(command);
}
catch (DbException ex)
{
throw new DataException(ex);
}
return reader;
}
EDIT My complete Store Procedure
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
--[dbo].[ImportIntoFirefighter] '''Vijay'',''Rana'',''AC'',''AC'',''VOL'',1,0,0,1,1,''NA'','''',''VOL'','''','''',0,'''','''',0,1,1,'''',0&''Vijay21'',''Rana2'',''AC'',''AC'',''VOL'',1,0,0,1,1,''NA'','''',''VOL'','''','''',0,'''','''',0,1,1,'''',0&''Vijay32'',''Rana3'',''AC'',''AC'',''VOL'',1,0,0,1,1,''NA'','''',''VOL'','''','''',0,'''','''',0,1,1,'''',0&''Vijay42'',''Rana4'',''AC'',''AC'',''VOL'',1,0,0,1,1,''NA'','''',''VOL'','''','''',0,'''','''',0,1,1,'''',0'
ALTER PROCEDURE [dbo].[ImportIntoFirefighter]
#query VARCHAR(MAX)
AS
BEGIN
DECLARE #TotalRecord int
DECLARE #loopcount int
DECLARE #TempQueryList TABLE
(
[ID] INT IDENTITY(1,1),
[VALUE] VARCHAR(1000)
)
DECLARE #Result TABLE
(
[iff_id] INT IDENTITY(1,1),
[last_name] VARCHAR(50),
[first_name] VARCHAR(50),
[email] VARCHAR(50),
[mobile_number] VARCHAR(50),
[error] VARCHAR(max)
)
insert into #TempQueryList (VALUE) (
SELECT SUBSTRING('&' + #query + '&', Number + 1,
CHARINDEX('&', '&' + #query + '&', Number + 1) - Number -1)AS VALUE
FROM master..spt_values
WHERE Type = 'P'
AND Number <= LEN('&' + #query + '&') - 1
AND SUBSTRING('&' + #query + '&', Number, 1) = '&' )
Set #TotalRecord = (select count(*) FROM #TempQueryList)
--select * from #TempQueryList
--Loop For Each Repeated Schedule
set #loopcount = 1
WHILE #loopcount <= #TotalRecord
BEGIN
Declare #SingleQuery varchar(1000)
select #SingleQuery = Value from #TempQueryList where id = #loopcount
BEGIN TRY
--print '[AddFirefighter] ' + #SingleQuery
--SELECT 1/0;
--execute (#SingleQuery)
declare #FinalQuery varchar(max)
-- Select #SingleQuery = LEFT(RIGHT(#SingleQuery, len(#SingleQuery)-1),len(#SingleQuery)-2)
set #FinalQuery = '[AddFirefighter] ' + #SingleQuery
print #FinalQuery
EXEC (#FinalQuery)
END TRY
BEGIN CATCH
insert into #Result (last_name,first_name,email,mobile_number,error) values ( '','','','',ERROR_MESSAGE() )
-- Execute the error retrieval routine.
END CATCH
--print #loopcount
SET #loopcount = #loopcount + 1
END
select * from #Result
--execute (#query)
END
Well ' is the delimiter so it seems to me your string becomes 'Vijay','Rana',1,0 I think you are mixing strings and numerics in the same "string" what you need to do is pass 'Vijay','Rana','1','0' (a string of strings) and then sort things out inside your procedure. To do this your passed string should be something like ' '' Vijay'',''Rana'',''1'',''0'' '. Depending on how you handle things inside your stored proc you may even need '' '''' Vijay'''',''''Rana'''',''''1'''',''''0'''' '' .Best create a simple proc which just returns the string as a test bed
If you are using c# and asp.net, you should set up your parameters in code rather then building a dynamic sql statement. If you already have the stored procedure setup then I'm not seeing a reason to call a dynamic sql statement and building out the parameters in a string.
Here is a example of a parameterized call to sql with a stored procedure.
http://msdn.microsoft.com/en-us/library/yy6y35y8(v=vs.110).aspx
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create the command and set its properties.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SalesByCategory";
command.CommandType = CommandType.StoredProcedure;
// Add the input parameter and set its properties.
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#CategoryName";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;
// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter);
// Open the connection and execute the reader.
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}: {1:C}", reader[0], reader[1]);
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
If your stored procedure takes four parameters as it seems to based on your question, you can add the parameters to a SqlCommand and then execute the command.
//Build your command
SqlConnection conn = new SqlConnection(yourConnectionString);
SqlCommand cmd = new SqlCommand("stored_procedure_name", conn);
cmd.CommandType = CommandType.StoredProcedure;
//Define the parameters to pass to the stored procedure
cmd.Parameters.Add("#firstParameter", SqlDbType.NVarChar, 255);
cmd.Parameters.Add("#secondParameter", SqlDbType.NVarChar, 255);
cmd.Parameters.Add("#thridParameter", SqlDbType.Int);
cmd.Parameters.Add("#fourthParameter", SqlDbType.Int);
//Assign Values to the parameters
cmd.Parameters["#firstParameter"].Value = "Vijay";
cmd.Parameters["#secondParameter"].Value = "Rana";
cmd.Parameters["#thirdParameter"].Value = 1;
cmd.Parameters["#fourthParameter"].Value = 0;
//Execute the command
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();

I want to insert a record in DB and then need to return a row

I want to insert a record in DB and then need to return a row. I created the query but how to use that in .cs (C# code)
This is my query
#ledgerId numeric(18,0) ,
#voucherNo varchar(MAX) ,
#invoiceNo varchar(MAX) ,
#date datetime ,
#month datetime ,
#totalAmount decimal(18,5) ,
#narration varchar(MAX) ,
-- #extraDate datetime ,
#extra1 varchar(MAX) ,
#extra2 varchar(MAX) ,
#suffixPrefixId numeric(18,0) ,
#voucherTypeId numeric(18,0)
AS
DECLARE #UpdatedVoucherNo DECIMAL(18,0)
SET #UpdatedVoucherNo = (SELECT ISNULL( MAX(CAST (voucherNo AS NUMERIC(18,0))),0) + 1
FROM tbl_SalaryVoucherMaster
WHERE voucherTypeId=#voucherTypeId)
IF (#UpdatedVoucherNo = #voucherNo )
INSERT INTO tbl_SalaryVoucherMaster
(
/*salaryVoucherMasterId,*/
ledgerId,
voucherNo,
invoiceNo,
date,
month,
totalAmount,
narration,
extraDate,
extra1,
extra2,
suffixPrefixId,
voucherTypeId )
VALUES
(
/*#salaryVoucherMasterId, */
#ledgerId,
#voucherNo,
#invoiceNo,
#date,
#month,
#totalAmount,
#narration,
getDate(),
#extra1,
#extra2,
#suffixPrefixId,
#voucherTypeId)
SELECT SCOPE_IDENTITY() AS [Identity],0 AS [UpdatedVoucherNo]
One way to do what you want is to modify #voucherNo to be an OUTPUT parameter, and add a new OUTPUT parameter to your query to return the value of SCOPE_IDENTITY().
#voucherNo varchar(max)
#ScopeIdentity numeric(38,0)
And modify that last SELECT statement to set the value of #ScopeIdentity parameter.
SELECT #ScopeIdentity = SCOPE_IDENTITY()
Then use SqlCommand.ExecuteNonQuery to execute the query, and on completion, read the values from the output parameters.
using (SqlCommand command = new SqlCommand(connection, commandText))
{
int rowsAffected = command.ExecuteNonQuery();
if (rowsAffected > 0)
{
var voucherNo = (string)command.Parameters["#voucherNo].Value;
var identity = (decimal)command.Parameters["#ScopeIdentity"].Value;
}
}
Command.ExecuteNonQuery(); is what you need, it returns the number(int) of rows affected in inserting and updating data,
here is an example to use it,
string connetionString = null;
SqlConnection cnn ;
SqlCommand cmd ;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Your SQL Statemnt Here";
cnn = new SqlConnection(connetionString);
cnn.Open();
cmd = new SqlCommand(sql, cnn);
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected > 0)
{
//do anything
}
cmd.Dispose();
cnn.Close();
MessageBox.Show (" ExecuteNonQuery in SqlCommand executed !!");
more information here

Getting return value from stored procedure in ADO.NET

I have a stored procedure, which returns the unique identifier after insertion ##identity. I tried it in the server explorer and it works as expected #RETURN_VALUE = [identifier].
In my code I added a parameter called #RETURN_VALUE, with ReturnValue direction first, than any other parameters, but when I run my query with ExecuteNonQuery() that parameter remains empty. I don't know what I've done wrong.
Stored Procedure
ALTER PROCEDURE dbo.SetAuction
(
#auctionID int,
#itemID int,
#auctionType tinyint,
#reservationPrice int,
#maxPrice int,
#auctionEnd datetime,
#auctionStart datetime,
#auctionTTL tinyint,
#itemName nchar(50),
#itemDescription nvarchar(MAX),
#categoryID tinyint,
#categoryName nchar(50)
) AS
IF #auctionID <> 0
BEGIN
BEGIN TRAN T1
UPDATE Auction
SET AuctionType = #auctionType,
ReservationPrice = #reservationPrice,
MaxPrice = #maxPrice,
AuctionEnd = #auctionEnd,
AuctionStart = #auctionStart,
AuctionTTL = #auctionTTL
WHERE AuctionID = #auctionID;
UPDATE Item
SET
ItemName = #itemName,
ItemDescription = #itemDescription
WHERE
ItemID = (SELECT ItemID FROM Auction WHERE AuctionID = #auctionID);
COMMIT TRAN T1
RETURN #auctionID
END
ELSE
BEGIN
BEGIN TRAN T1
INSERT INTO Item(ItemName, ItemDescription, CategoryID)
VALUES(#itemName, #itemDescription, #categoryID);
INSERT INTO Auction(ItemID, AuctionType, ReservationPrice, MaxPrice, AuctionEnd, AuctionStart, AuctionTTL)
VALUES(##IDENTITY,#auctionType,#reservationPrice,#maxPrice,#auctionEnd,#auctionStart,#auctionTTL);
COMMIT TRAN T1
RETURN ##IDENTITY
END
C# Code
cmd.CommandText = cmdText;
SqlParameter retval = new SqlParameter("#RETURN_VALUE", System.Data.SqlDbType.Int);
retval.Direction = System.Data.ParameterDirection.ReturnValue;
cmd.Parameters.Add(retval);
cmd.Parameters.AddRange(parameters);
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
return (int)cmd.Parameters["#RETURN_VALUE"].Value;
Just tried on my box and this works for me:
In SQL Server:
DROP PROCEDURE TestProc;
GO
CREATE PROCEDURE TestProc
AS
RETURN 123;
GO
In C#
string cnStr = "Server=.;Database=Sandbox;Integrated Security=sspi;";
using (SqlConnection cn = new SqlConnection(cnStr)) {
cn.Open();
using (SqlCommand cmd = new SqlCommand("TestProc", cn)) {
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter returnValue = new SqlParameter();
returnValue.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(returnValue);
cmd.ExecuteNonQuery();
Assert.AreEqual(123, (int)returnValue.Value);
}
}
I solved the problem:
you have to set SqlCommand.CommandType to CommandType.StoredProcedure in order to get return values and/or output parameters. I haven't found any documentation about that, but now everything works.
Do you get the value of you EXEC in TSQL? I wonder if refactoring the TSQL would help (and using SCOPE_IDENTITY():
so change:
COMMIT TRAN T1
RETURN ##IDENTITY
to:
SET #auctionID = SCOPE_IDENTITY()
COMMIT TRAN T1
RETURN #auctionID
(I would also change the other ##IDENTITY to SCOPE_IDENTITY())
As a minor optimisation, you could also use:
return (int)retval.Value;
but this side of things should have worked "as is" from what I can see (hence why I'm focusing on the TSQL).
Some one can also use this simple and short method to calculate return value from SP
In SQL:
Create Table TestTable
(
Int Id
)
CREATE PROCEDURE Proc_TestProc
#Id
AS
Begin
Set NOCOUNT ON //Use this line if you don't want to return any message from SQL
Delete from TestTable where Id = #Id
return 1
Set NOCOUNT OFF //NOCOUNT OFF is Optional for NOCOUNT ON property
End
Sql Server always returns Int type value only.
and in C#
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TestConnectionString"].ToString()))
using (SqlCommand cmd = new SqlCommand("Proc_TestProc", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Id", 1);
var returnParameter = cmd.Parameters.Add("#ReturnVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
conn.Open();
cmd.ExecuteNonQuery();
var result = returnParameter.Value;
}
You can also check your return value in SQL by using this command:
DECLARE #return_status int;
EXEC #return_status = dbo.[Proc_TestProc] 1;
SELECT 'Return Status' = #return_status;
print 'Returned value from Procedure: ' + Convert(varchar, #return_status); // Either previous or this line both will show you the value of returned value
you can use standart ways that you use before in normal queries but in Sql command you must write EXEC before your store procedure name and dont use commandtype like this :
SqlConnection con = new SqlConnection(["ConnectionString"])
SqlCommand com = new SqlCommand("EXEC _Proc #id",con);
com.Parameters.AddWithValue("#id",["IDVALUE"]);
con.Open();
SqlDataReader rdr = com.ExecuteReader();
ArrayList liste = new ArrayList();
While(rdr.Read())
{
liste.Add(rdr[0]); //if it returns multiple you can add them another arrays=> liste1.Add(rdr[1]) ..
}
con.Close();

Categories