Retrieve two strings from a stored procedure result to strings - c#

[SCHOOL WORK]
I have a stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [IO].[usp_selectUser] (#username varchar(50))
AS
BEGIN
SELECT passwordSalt, hashedPassword
FROM [IO].[Users]
WHERE username = #username;
END
And in my C# program I need to get the passwordSalt and the hashedPassword where username matches:
Current C# code:
SqlCommand command = new SqlCommand("[IO].[usp_selectUser]", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#username", SqlDbType.VarChar)).Value = username;
I've tried some stuff from Google search results, but none of the worked properly. How do I get two individual strings?

A friend solved my problem. The stored procedure didn’t have marked parameters as output.
USE [TICKETING_DB]
GO
/****** Object: StoredProcedure [IO].[usp_selectUser] Script Date: 5/4/2020 11:08:10 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [IO].[usp_selectUser] (#username varchar(50), #passwordSalt varchar(50) output, #hashedPassword varchar(100) output)
AS
BEGIN
SELECT #passwordSalt = passwordSalt, #hashedPassword = hashedPassword FROM [IO].[Users]
WHERE username = #username;
END

Related

stored procedure returns varchar c# sql server

I need input one variable and output another
CREATE PROC CheckLogPas2
#log varchar(Max)
as
BEGIN
SET NOCOUNT ON;
DECLARE #k varchar(50);
set #k = (SELECT position From sotrud_users where login = #log);
RETURN #k;
END
in this procedure i want take in variable "k" "position". "position" is varchar. When i try use it procedure give error. I can't output variable "k" because RETURN can't output not int variable
SqlCommand sqlcmd = new SqlCommand("[CheckLogPas]", conn);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddWithValue("#log", SqlDbType.Int);
sqlcmd.Parameters["#UserID"].Value = DB_values.check_log;
SqlParameter param = new SqlParameter();
param.ParameterName = "#k";
param.SqlDbType = SqlDbType.NVarChar;
param.Direction = ParameterDirection.ReturnValue;
sqlcmd.ExecuteNonQuery();
comm.Parameters.Add(param);
conn.Open();
comm.ExecuteNonQuery();
pos = param.Value;
and this my code in c#. i need to get a variable in another variable string on c#
I believe a Scalar-valued Function would solve your problem, instead of a Stored Procedure. Using this you would be able to create a function in SQL Server that accepts parameters, and can return a value. If you wish to return more than one value from your function, you would need to use a Table-valued Function instead.
Here is the structure for a Scalar-valued function:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date, ,>
-- Description: <Description, ,>
-- =============================================
CREATE FUNCTION <Scalar_Function_Name, sysname, FunctionName>
(
-- Add the parameters for the function here
<#Param1, sysname, #p1> <Data_Type_For_Param1, , int>
)
RETURNS <Function_Data_Type, ,int>
AS
BEGIN
-- Declare the return variable here
DECLARE <#ResultVar, sysname, #Result> <Function_Data_Type, ,int>
-- Add the T-SQL statements to compute the return value here
SELECT <#ResultVar, sysname, #Result> = <#Param1, sysname, #p1>
-- Return the result of the function
RETURN <#ResultVar, sysname, #Result>
END
GO
And here is how a Table-valued Function would be structured:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE FUNCTION <Inline_Function_Name, sysname, FunctionName>
(
-- Add the parameters for the function here
<#param1, sysname, #p1> <Data_Type_For_Param1, , int>,
<#param2, sysname, #p2> <Data_Type_For_Param2, , char>
)
RETURNS TABLE
AS
RETURN
(
-- Add the SELECT statement with parameter references here
SELECT 0
)
GO
Your current stored procedure:
CREATE PROC CheckLogPas2
#log varchar(Max)
as
BEGIN
SET NOCOUNT ON;
DECLARE #k varchar(50);
set #k = (SELECT position From sotrud_users where login = #log);
RETURN #k;
END
Could be re-written as a Scalar-valued function like so:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date, ,>
-- Description: <Description, ,>
-- =============================================
CREATE FUNCTION CheckLogPas2
(
-- Add the parameters for the function here
#log nvarchar(max)
)
RETURNS nvarchar(max)
AS
BEGIN
RETURN (SELECT position From sotrud_users where login = #log)
END
GO
Using that, you could instead have your c# code execute the following query:
SELECT [dbo].[CheckLogPas2](#log);
Like so:
// using a command to retrieve
using (SqlCommand cmd = new SqlCommand("SELECT [dbo].[CheckLogPas2](#log);", conn))
{
// format command
cmd.Parameters.Add("#log", SqlDbType.NVarChar).Value = yourLogVariable;
// get a sqlreader with the results from our query
using (SqlDataReader reader = cmd.ExecuteReader())
{
if(reader.Read())
{
string desiredStringResult = reader.GetString(0);
}
}
}

C# MVC - SP not insert values

I'm trying to make an insert from my controller to my database. I already debug and it never enter on the exception. But i can not see the values on the db.
This is my sp:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[RegisterUser]
-- Add the parameters for the stored procedure here
#Username nvarchar(10),
#Password nvarchar(10),
#Mail nvarchar(10),
#Birthday date
AS
BEGIN
SET NOCOUNT ON
INSERT INTO Users
(
Username,
Pass,
Mail,
Birthday
)
VALUES
(
#Username,
#Password,
#Mail,
#Birthday
)
END
And on my model i used this method:
public bool registerUser(UserModel user)
{
bool isOk = false;
using (SqlConnection connection = DbConnection.OpenConnection2())
{
try
{
using (SqlCommand command = new SqlCommand("RegisterUser", connection))
{
command.CommandType = CommandType.StoredProcedure;
SqlCommandBuilder.DeriveParameters(command);
command.Parameters.Add(new SqlParameter("#UserName", SqlDbType.VarChar)).Value = user.userName.Trim();
command.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar)).Value = user.password.Trim();
command.Parameters.Add(new SqlParameter("#Mail", SqlDbType.VarChar)).Value = user.mail.Trim();
command.ExecuteNonQuery();
}
}
catch (Exception e)
{
}
finally
{
if (connection.State.Equals(ConnectionState.Open))
{
connection.Close();
isOk = true;
}
}
}
return isOk;
}
Any ideas of why this is not working?
Thanks
Things are easy, if you use exception handling in a proper manner. You are swallowing the exception thrown by Ado.net. Follow these steps for solving your problem:
First of all you should add a throw statement in your catch block to get the exception being thrown. In production, You should catch that at later calling function or layer.
You need to provide all the parameters to your stored procedure. Currently, You are not passing one parameter named #Birthday and its value. Add this parameter with its value.
Here is the modified code that should work.
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#UserName", SqlDbType.VarChar)).Value = user.userName.Trim();
command.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar)).Value = user.password.Trim();
command.Parameters.Add(new SqlParameter("#Mail", SqlDbType.VarChar)).Value = user.mail.Trim();
//Assuming that the user object has a field named Birthday
command.Parameters.Add(new SqlParameter("#Birthday", SqlDbType.Date)).Value = user.Birthday;
command.ExecuteNonQuery();
If you follow my first advice, you will nearly get any other problem that is occurring in your code.
I hope it will help you somehow. Thanks!
If you prefer, you can provide a default value for the parameter #Birthday as:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[RegisterUser]
-- Add the parameters for the stored procedure here
#Username nvarchar(10),
#Password nvarchar(10),
#Mail nvarchar(10),
#Birthday date = NULL
AS
BEGIN
SET NOCOUNT ON
INSERT INTO Users
(
Username,
Pass,
Mail,
Birthday
)
VALUES
(
#Username,
#Password,
#Mail,
#Birthday
)
END
If you are not supplying "#Birthday" parameter, Please specify "#Birthday date" as "#Birthday date = NULL" in the stored procedure as below:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[RegisterUser]
-- Add the parameters for the stored procedure here
#Username nvarchar(10),
#Password nvarchar(10),
#Mail nvarchar(10),
#Birthday date = NULL
AS
BEGIN
SET NOCOUNT ON
INSERT INTO Users
(
Username,
Pass,
Mail,
Birthday
)
VALUES
(
#Username,
#Password,
#Mail,
#Birthday
)
END
Rest of your code looks all good to me.
Hope this will help you.

Bulk Update stored procedure with user input (WITHOUT A DATATABLE)

Can I perform a bulk update using a stored procedure that sends data to a temp table from user input which is not in a datatable.
If I have a foreach loop that takes user input such as values from a checkboxlist and text boxes what I want to know is how to parameterize those separate values in my stored procedure or if I can do it in my code. I cannot use table-valued parameters since I'm using a version of SQL that does not support it.
conn.Open();
foreach(ListItem item in CheckBoxList1.Items)
{
if(item.Selected)
{
//handling parameters in loop.
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Update_Account_Table";
cmd.Parameters["#SeqNum"].Value = amount.Text;
cmd.Parameters["#SeqDate"].Value = DateTime.ParseExact(datepicker.Text, "mmddyyyy", CultureInfo.InvariantCulture);
cmd.Parameters["#Account_ID"].CheckBoxList1.SelectedValue;
cmd.ExecuteNonQuery();
}
conn.Close();
}
Stored procedure
CREATE TABLE TempTable
(
SeqNum int,
SeqDate datetime,
Account_ID varchar(2)
);
CREATE PROCEDURE [ACCOUNTTABLE_UPDATE]
AS
SET NOCOUNT ON
BEGIN
UPDATE AccountTable
SET SeqNum = t.SeqNum, SeqDate = t.SeqDate
FROM AccountTable AT
INNER JOIN TempTable t ON AT.AccountID = t.AccountID
END
This uses a dynamic table name in stored procedure, and sets value based on incoming parameter. You could use code below instead of temp table, or use parameters #seqnum, #SeqDate, #AcctID in place of #Stats_Value below:
USE [EODData]
GO
/****** Object: StoredProcedure [dbo].[erase_Stats] Script Date: 8/23/2016 4:32:55 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[erase_Stats]
#table varchar(25), #stats_value int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Declare #ProductsSQL nvarchar(max);
SET #ProductsSQL = 'update ' + #table + ' set stats_completed = #Stats_Value'
exec sp_executesql #ProductsSQL
END
GO
you can add # before the table to make it temporary table
your should be like
CREATE TABLE #TempTable
will create temporary table and destroyed after process completes

Stored procedure gives an empty reader

I have the following Stored procedure
ALTER PROCEDURE dbo.USER_AUTH
(
#username varchar,
#password varchar
)
AS
BEGIN
SELECT * FROM users
WHERE username = #username
AND password = #password;
END
And there are Two rows in the users table.
This gives an empty reader error
_Command = new SqlCommand("[dbo].[USER_AUTH]", _Connection);
_Command.CommandType = System.Data.CommandType.StoredProcedure;
_Command.Parameters.AddWithValue("#username", _Username);
_Command.Parameters.AddWithValue("#password", _Password);
reader = _Command.ExecuteReader();
While this works fine
_Command = new SqlCommand("select * from users where
username=#username and password=#password" , _Connection);
_Command.Parameters.AddWithValue("#username", _Username);
_Command.Parameters.AddWithValue("#password", _Password);
reader = _Command.ExecuteReader();
Where _Connection is SqlConnection _Connection , _Command is SqlCommand _Command and
reader is SqlDataReader
This happens because your stored procedure declares
ALTER PROCEDURE dbo.USER_AUTH
(
#username varchar,
#password varchar
)
without specifying a size for the two varchars. In this way just one char is passed to the parameters and of course nothing is retrieved
Change the sp to
ALTER PROCEDURE dbo.USER_AUTH
(
#username nvarchar(30),
#password nvarchar(30)
)
or whatever size are your two database fields
You have to specify the length for varchar
So if we don't specify the length ourself these are the default values SQL Server uses - which means the data what we would be expecting to get stored in the database would have got silently truncated without our knowledge.
Bad habits to kick : declaring VARCHAR without (length)
ALTER PROCEDURE dbo.USER_AUTH
(
#username varchar(20),
#password varchar(20)
)
AS
BEGIN
SELECT * FROM users
WHERE username = #username
AND password = #password;
END

unable to insert data in table in web application?

I am trying to write procedure for insert value into table but the value not inserted in table
for reference I am give code which i had try for it...can anyone please help me
for insert i am try this code
public int Visitor_Insert(visitor_Master visitor_obj, common_Class comm_obj)
{
DB_Connection();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT_VISITOR";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#VISITOR_NAME", visitor_obj.VisitorName);
cmd.Parameters.AddWithValue("#VISITOR_CONTACT", visitor_obj.VisitorContact);
cmd.Parameters.AddWithValue("#VISITOR_ADDRESS", visitor_obj.VisitorAddress);
cmd.Parameters.AddWithValue("#VISITOR_AGE", visitor_obj.VisitorAge);
cmd.Parameters.AddWithValue("#VISITOR_VEHICLENO", visitor_obj.VisitorVehicleNO);
//cmd.Parameters.AddWithValue("#VISITOR_AGE ", visitor_obj.VisitorAge);
int i = cmd.ExecuteNonQuery();
return i;
}
For Procedure I am written this code
USE [VPMS]
GO
/****** Object: StoredProcedure [dbo].[INSERT_VISITOR] Script Date: 07/24/2013 16:01:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[INSERT_VISITOR]
#VISITOR_NAME NVARCHAR(30),
#VISITOR_CONTACT NVARCHAR(10),
#VISITOR_ADDRESS NVARCHAR(40),
#VISITOR_AGE NVARCHAR(2),
#VISITOR_VEHICLENO NVARCHAR(20),
#VISITOR_IMAGE IMAGE,
#VISITOR_CREATEDBY NVARCHAR(20),
#VISITOR_CREDTEDON NVARCHAR(20),
#VISITOR_MODIFIEDBY NVARCHAR(20),
#VISITOR_MODIFIEDON NVARCHAR(20)
AS
DECLARE #VISITOR_ID INT,
BEGIN
SET NOCOUNT ON;
SELECT #VISITOR_ID= MAX(Visitor_Id) FROM Visitor_Master
IF (#VISITOR_ID > 0 )
BEGIN
SET #VISITOR_ID=#VISITOR_ID+1
END
ELSE
BEGIN
SET #VISITOR_ID=10
END
INSERT INTO Visitor_Master( Visitor_Id, VisitorName, Visitor_Contact, Visitor_Address, Visitor_age,
Visitor_VehicleNo, Visitor_Image, Created_By, Created_On, Modify_By, Modify_On)
VALUES(#VISITOR_ID,#VISITOR_NAME,#VISITOR_CONTACT,#VISITOR_ADDRESS,#VISITOR_AGE,#VISITOR_VEHICLENO,#VISITOR_IMAGE,#VISITOR_CREATEDBY,
#VISITOR_CREDTEDON,#VISITOR_MODIFIEDBY,#VISITOR_MODIFIEDON)
END
As you are not passing all the parameters defined in the procedure. It will throw exception.
Here I have assigned null to other parameters which you have not specified assign value as per your reqirement
ALTER PROCEDURE [dbo].[INSERT_VISITOR]
#VISITOR_NAME NVARCHAR(30),
#VISITOR_CONTACT NVARCHAR(10),
#VISITOR_ADDRESS NVARCHAR(40),
#VISITOR_AGE NVARCHAR(2),
#VISITOR_VEHICLENO NVARCHAR(20),
#VISITOR_IMAGE IMAGE = null,
#VISITOR_CREATEDBY NVARCHAR(20) = null,
#VISITOR_CREDTEDON NVARCHAR(20) = null,
#VISITOR_MODIFIEDBY NVARCHAR(20) = null,
#VISITOR_MODIFIEDON NVARCHAR(20) = null
-- rest of code
You have #VISITOR_IMAGE,#VISITOR_CREATEDBY,#VISITOR_CREDTEDON,#VISITOR_MODIFIEDBY,#VISITOR_MODIFIEDON parameters in your procedure but you have not passed value to the the above parameter.Either pass value to all the parameters or allow null
BEGIN
set #VISITOR_IMAGE = null,
set #VISITOR_CREATEDBY = null,
set #VISITOR_CREDTEDON = null,
set #VISITOR_MODIFIEDBY = null,
set #VISITOR_MODIFIEDON = null
........

Categories

Resources