I have the following function;
public int GetLoginClaim(IsValidLogin Obj)
{
SqlConnection DBCon = new SqlConnection(ConString);
SqlCommand CmdSelect = new SqlCommand("IsValidLogin", DBCon);
CmdSelect.CommandType = CommandType.StoredProcedure;
DBCon.Open();
try
{
CmdSelect.Parameters.AddWithValue("#UserName", Obj.Username);
CmdSelect.Parameters.AddWithValue("#Password", Obj.Password);
return (int)CmdSelect.ExecuteScalar();
}
catch
{
throw;
}
finally
{
CmdSelect.Dispose();
DBCon.Close();
DBCon.Dispose();
}
}
And the following stored procedure on which it depends;
USE [SMania]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[IsValidLogin]
#UserName varchar(32),
#Password varchar(32)
As
if exists(Select * From NewClientTB Where UserName = #UserName And Password = #Password)
return(1)
else
return(0)
The stored procedure is working correctly when executed on sql server, but when called from the function i posted above, it gives error. The above function is in my data access layer. So in the stack trace, i am having the following error on the above function:
NullReferenceException: Object reference not set to an instance of an object. Can anyone fix this problem?
You need different approach for SPs with return status
Check the example on this MSDN article http://msdn.microsoft.com/en-us/library/ms378371(v=sql.90).aspx
If you want to use ExecuteScalar you need to replace return(X) with select X in SP because it "returns the first column of the first row in the result set" but there is no result set in your SP only return value.
This is how you can get return status in C#
CmdSelect.Parameters.AddWithValue("#UserName", Obj.Username);
CmdSelect.Parameters.AddWithValue("#Password", Obj.Password);
var return_state = CmdSelect.Parameters.Add("#ReturnVal", SqlDbType.Int);
return_state.Direction = ParameterDirection.ReturnValue;
CmdSelect.ExecuteNonQuery();
return (int)return_state.Value;
Related
I want the date and the name from the select query which if I run as normal query I get the results but i when I try to get the results in C# all I get is count=0. Can anyone tell me what wrong am I doing?
Here is the C# code
private List<CertificationSummary> GetLastAccessData (string taskOwner)
{
List<CertificationSummary> lastAccessedResult = new List<CertificationSummary>();
string connectionString = SqlPlusHelper.GetConnectionStringByName("MetricRepositoryDefault");
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlParameter[] sqlParams = new SqlParameter[1];
sqlParams[0] = new SqlParameter("#taskOwner", SqlDbType.NVarChar);
sqlParams[0].Value = taskOwner;
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetLastAccessedCertificationData";
cmd.Parameters.AddRange(sqlParams);
cmd.ExecuteNonQuery();
}
return lastAccessedResult;
}
And here is the stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetLastAccessedCertificationData]
(#taskOwner nvarchar(255))
AS
BEGIN
DECLARE #name nvarchar(100)
DECLARE #lastAccessedDate [datetime]
SELECT #name = Name
FROM CertificationReviewCycles
INNER JOIN UserReviewCycleAccess ON CertificationReviewCycles.CertificationReviewCycleID = UserReviewCycleAccess.LastAccessedReviewCycleID
WHERE USERID = #taskOwner
SELECT #lastAccessedDate = LastAccessedDate
FROM UserReviewCycleAccess
WHERE UserID = #taskOwner
CREATE TABLE #tempTable
(
name [nvarchar](255) NULL,
[LastAccessedDate] [datetime] NULL,
)
INSERT INTO #tempTable VALUES (#name, #lastAccessedDate)
SELECT TOP(1) name, LastAccessedDate
FROM #tempTable
END
GO
You are returning lastAccessedResult which is has just been set to new List<CertificationSummary>(). This list has no items, so it has a count of 0.
Use ExecuteReader instead of ExecuteNonQuery and you can then read the data returned and store them into your lastAccessedResult list.
Read here for more info.
ExecuteNonQuery will not return results, and should only be used when you don't expect rows back. This is common for UPDATE statements.
Since you're interested in reading the rows returned by the stored procedure, use ExecuteReader, e.g var reader = cmd.ExecuteReader();
See here for more:
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader?view=dotnet-plat-ext-3.1
You're using ExecuteNonQuery, which discards any grids from the query. You need to use ExecuteReader to consume grids, but it is a lot of mess and ceremony - the API is verbose. Frankly, I'd recommend a tool like "Dapper" (freely available on NuGet), then this becomes just
private List<CertificationSummary> GetLastAccessData (string taskOwner)
{
string connectionString = SqlPlusHelper.GetConnectionStringByName("MetricRepositoryDefault");
using var connection = new SqlConnection(connectionString);
return connection.Query<CertificationSummary>(
"GetLastAccessedCertificationData",
new { taskOwner }, // <== parameters
commandType: CommandType.StoredProcedure).AsList();
}
I have a stored procedure called lastID like this:
CREATE PROCEDURE lastID(#id varchar(64) OUTPUT)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #f VARCHAR(64);
SELECT TOP 1 #f = work_id
FROM workorder
WHERE (RIGHT(work_id,2)) = (RIGHT(Year(getDate()),2))
ORDER BY work_id DESC;
IF(#f IS NULL)
BEGIN
SET #f = 'No work orders';
SET #id = #f;
RETURN #id;
END
ELSE
BEGIN
SET #id = #f;
RETURN #id;
END
END
This stored procedure returns the last id from the table workorder, now I'm trying to execute this procedure in C#, this is the code:
private void lastWorkId()
{
String strConnString = "Server=.\\SQLEXPRESS;Database=recalls;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "lastID";
cmd.Parameters.Add("#id", SqlDbType.VarChar, 64).Direction = ParameterDirection.Output;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
String id = cmd.Parameters["#id"].Value.ToString();
lastid.Text = id.ToString(); //Putting the return value into a label
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
I don't know what are wrong with my code, because an exception is displayed, and this says
Conversion failed when converting the varchar value ' OT- 003-16 ' to data type int
I was wrong about my first answer, here is the updated answer:
Your stored procedure is setup with an OUTPUT parameter of type VARCHAR(64).
Within your proc you have a couple of RETURN #id; statements, which is actually returning a VARCHAR(64). You only need to set your OUTPUT variable within the stored procedure. The RETURN statement expects an integer expression. Here's the updated fixed sproc using OUTPUT appropriately:
ALTER PROCEDURE [dbo].[lastID](#id varchar(64) OUTPUT)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #f VARCHAR(64);
SELECT TOP 1 #f = work_id FROM workorder WHERE (RIGHT(work_id,2)) = (RIGHT(Year(getDate()),2)) ORDER BY work_id DESC;
IF(#f IS NULL)
BEGIN
SET #f = 'No work orders';
SET #id = #f;
END
ELSE
BEGIN
SET #id = #f;
END
END
Error is basically should get fixed by cast
((RIGHT(work_id,2)) as int)
But code can be further condensed and improved.
CREATE PROCEDURE lastID(#id varchar(64) OUTPUT)
AS
BEGIN
SET NOCOUNT ON;
SELECT TOP 1 #id = isnull(work_id , 'No work orders') FROM workorder WHERE cast ((RIGHT(work_id,2)) as int)= (RIGHT(Year(getDate()),2)) ORDER BY work_id DESC;
RETURN #id;
END
I need to get an employees start date. What I am trying to do is when a check box is checked make a call to the database get the date and return it into my C# code. I think I have everything set-up close to perfect, but my call procedure returns an error. Can someone assist me with setting up syntax so that when a check box is checked it will make a call to the database, run a stored procedure, and return the result (as a datetime) from the stored procedure back into my C# syntax?
EDIT --- The error being thrown is:
cannot implicitly convert type 'System.DateTime' to 'string'
//Calling Procedure
this.txtStartDate.Text = getHireDate(Constants.Database, employeename);
//Actual Procedure
private static string getHireDate(string Database, string employeename)
{
SqlConnection connection = new SqlConnection(Database);
SqlCommand command = new SqlCommand("_uspGetHireDate", connection);
command.CommandType = CommandType.StoredProcedure;
SqlParameter returnValue = new SqlParameter("returnVal", SqlDbType.Int);
returnValue.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(returnValue);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
//This line throws an error of can not implicitly convert 'System.DateTime' to 'string'
return Convert.ToDateTime(returnValue.Value);
}
//Stored Procedure Being Called
alter procedure [dbo].[_uspGetHireDate]
(
#employeename varchar(100)
)
as
declare #StartDate datetime
set NOCOUNT ON
Set #StartDate = (SELECT CONVERT(VARCHAR(10), HireDate, 101)
FROM tbl_employeeinformation
where hiredate is not null
AND active = 1
AND employeename = #employeename
return #StartDate
Your solution is totally messy. Why are you converting DATE to VARCHAR, then return it as an INT, then converting it as a DateTime and return as STRING???
First of all change your stored procedure to return value standard way. Return DATE, not INT with return:
alter procedure [dbo].[_uspGetHireDate]
#employeename varchar(100)
as
set NOCOUNT ON
SELECT HireDate
FROM tbl_employeeinformation
where hiredate is not null
AND active = 1
AND employeename = #employeename
Then change your method to return DateTime:
private static DateTime getHireDate(string Database, string employeename)
{
SqlConnection connection = new SqlConnection(Database);
SqlCommand command = new SqlCommand("_uspGetHireDate", connection);
command.CommandType = CommandType.StoredProcedure;
connection.Open();
var result = Convert.ToDateTime(command.ExecuteScalar());
connection.Close();
return result;
}
Thanks to #petelids for pointing this out. Change your presentation layer to:
this.txtStartDate.Text = getHireDate(Constants.Database, employeename).ToString("yyyy-MM-dd");
or whatever format that is appropriate. Visualizing data is a work of a presentation layer and not of a business layer. Here you are storing connection string in presentation layer and this is a bit of strange.
Also put your connections, commands etc in using blocks and use try-catch blocks.
Also I have noticed that you are not passing #employeename parameter to your stored procedure.
You are returning DateTime instead of string as intended in function return type
private static string getHireDate(string Database, string employeename)
{
----
return Convert.ToDateTime(returnValue.Value); // Here you are returning datetime but your return type should be string as your function return type is string
}
Trying to get Username by UserId - I have the following stored procedure:
ALTER PROCEDURE [dbo].[GET_UsernameByUserId_SP](
#UserId int,
#ExecutionResult nvarchar(64) OUTPUT
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SET #ExecutionResult = (SELECT TOP 1 Username FROM UserProfile WHERE UserId = #Userid);
END
Executed by the following method:
public string CallSpRetStr(String spName, SqlParameter[] sqlParams)
{
string sRet = null;
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.CommandText = spName;
myCommand.Parameters.Clear();
myCommand.Parameters.AddRange(sqlParams);
myCommand.Parameters.AddWithValue("#ExecutionResult", DbType.String);
myCommand.Parameters[myCommand.Parameters.Count - 1].Direction = ParameterDirection.Output;
try
{
if (myConnection.State == ConnectionState.Open)
{
myCommand.ExecuteNonQuery();
}
else
{
OpenConnection();
myCommand.ExecuteNonQuery();
CloseConnection();
}
sRet = myCommand.Parameters["#ExecutionResult"].Value.ToString();
}
catch (Exception ex)
{
CloseConnection();
}
return sRet;
}
Called by the following method:
public string GetUsernameByUserId(int UserId)
{
SqlParameter[] parameters = new SqlParameter[1];
parameters[0] = new SqlParameter("#UserId", UserId);
return dal.CallSpRetStr("GET_UsernameByUserId_SP", parameters);
}
At runtime I get the following error message (caught by the try-catch in CallSpRetStr):
'Error converting datatype nvarchar to int'.
I've been banging my head in the wall for more than hour now, trying crazy things etc.
I have two questions:
1. Does anyone understand what is the problem in all the above?
2. Is anyone aware of a better way to get the username by the userid?
Thanks in advance.
This line is incorrect
myCommand.Parameters.AddWithValue("#ExecutionResult", DbType.String);
should be
myCommand.Parameters.AddWithValue("#ExecutionResult", new string(' ', 64);
The AddWithValue method expects, for its second parameter, the current value for the named parameter but you pass an enum (DbType.String == (int)16). AddWithValue then tries to build a parameter with the datatype corresponding to the value passed and thus creates an integer parameter. Of course this is not acceptable by your stored procedure that expects a nvarchar type
Also I would remove any possible misunderstanding on which parameter is the output one using the return value from the AddWithValue instead of an indexing on the parameter collection
SqlParameter p myCommand.Parameters.AddWithValue("#ExecutionResult", new string(' ', 64);
p.Direction = ParameterDirection.Output;
Notice that we need to create a string of the correct size because AddWithValue doesn't know the expected size of the parameter from the stored procedure and so it creates the parameter with the size equals to the length of the string passed.
I am executing a stored procedure in c# (through vs2008) using ado.net with an ExecuteScalar command. The stored proc returns the pkey of the new record entered, but ExecuteScalar is returning null. I look in the database and a record has indeed been added. I could use an output parameter to get the value, but then I won't know why this didn't work.
When I execute the sp in ssms, the pkey is returned.
What am I doing wrong?
Here is the C# code:
public int SaveNewPerson(EPerson ePerson)
{
int newPersonPkey;
SqlConnection cn = new SqlConnection(cnn.PersonData);
using (cn)
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "People.dbo.AddNewPerson";
cmd.Parameters.Add("#LastName", SqlDbType.VarChar, 150).Value = ePerson.LastName;
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar, 150).Value = ePerson.FirstName;
cn.Open();
object result = cmd.ExecuteScalar();
newPersonPkey = int.Parse(result.ToString());
cn.Close();
}
catch (Exception e)
{
// call error method
throw new Exception(e.Message + " save new Person error ");
}
}
return newPersonPkey;
}
And this is the sp:
PROCEDURE [dbo].[AddNewPerson]
#FirstName varchar(50)
,#LastName varchar(50)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [People].[dbo].[Persons]
(
[FirstName]
,[LastName]
)
VALUES
(
#FirstName
,#LastName
)
declare #persons_PKey int
set #persons_PKey = ##IDENTITY
return #persons_PKey
end
The ExecuteScalar method returns the first field of the first record of the result, but as your query doesn't produce a result, it will return null.
You can either select the value instead of returning it from the stored procedure, or add a parameter with the direction set to ParameterDirection.ReturnValue to catch what the stored procedure returns.
Try changing the Stored Procedure to use a Select Statement to return the identity instead of using a return like this:
SELECT CAST(scope_identity() AS int)
Thus changing your procedure to:
PROCEDURE [dbo].[AddNewPerson]
#FirstName varchar(50)
,#LastName varchar(50)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [People].[dbo].[Persons]
(
[FirstName]
,[LastName]
)
VALUES
(
#FirstName
,#LastName
)
SELECT CAST(scope_identity() AS int)
end
From the documentation of the ExecuteScalar() on MSDN it says that it will return the first column of the first row in the result set or null otherwise if the result set is empty.