I am getting error as "Procedure or function 'Artical_i' expects parameter '#ID', which was not supplied.". But my #ID parameter is Output parameter.
-------------------------------c# Code----------------------------------------
int retVal=0;
SqlParameter outputParam = new SqlParameter();
outputParam.ParameterName = "#ID";
outputParam.SqlDbType = SqlDbType.Int;
outputParam.Direction = ParameterDirection.Output;
outputParam.Value = retVal; /// Added in Edit
SqlParameter[] sParam =
{
outputParam,
new SqlParameter("#Title",this.Title),
new SqlParameter("#BaseUri",this.BaseUri),
new SqlParameter("#Description",this.Description),
new SqlParameter("#ShortDescription",this.ShortDescription),
new SqlParameter("#Copyright",this.Copyright),
new SqlParameter("#ItemID",this.ItemID),
new SqlParameter("#LastUpdatedTime",this.LastUpdatedTime),
new SqlParameter("#PublishDate",this.PublishDate),
new SqlParameter("#SourceFeedURL",this.SourceFeedURL)
};
SqlConnection connection = new SqlConnection(connectionString)
SqlCommand command = new SqlCommand();
connection.Open();
command.Connection = connection;
command.CommandText = procedureName;
command.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter p in sParam )
{
command.Parameters.AddWithValue(p.ParameterName, p.Value);
}
command.ExecuteNonQuery(); /// Error Here as "Procedure or function 'Artical_i' expects parameter '#ID', which was not supplied."
retVal = Convert.ToInt32(outputParam.Value); // Value returned as 0 here
-------------------- Stored Procedure---------------------------
IF OBJECT_ID (N'Artical_i', N'P') IS NOT NULL
Begin
drop procedure Artical_i
End
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Procedure Artical_i
(
#Title nvarchar(500),
#BaseUri nvarchar(2083),
#Description nvarchar(max),
#ShortDescription nvarchar(500),
#Copyright nvarchar(250),
#ItemID varchar(250),
#LastUpdatedTime datetimeoffset(7),
#PublishDate datetimeoffset(7),
#SourceFeedURL nvarchar(2083),
#ID int OUTPUT
)
as
Begin
BEGIN TRY
BEGIN TRANSACTION
set nocount on;
INSERT INTO [dbo].[Artical]
([Title]
,[BaseUri]
,[Description]
,[ShortDescription]
,[Copyright]
,[ItemID]
,[LastUpdatedTime]
,[PublishDate]
,[CreatedDate]
,[SourceFeedURL])
VALUES
(#Title,
#BaseUri,
#Description,
#ShortDescription,
#Copyright,
#ItemID,
#LastUpdatedTime,
#PublishDate,
Getdate(),
#SourceFeedURL)
Select #ID =SCOPE_IDENTITY()
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
Select #ID =0
END CATCH
End
GO
Related
I have written stored procedure to get customer id with given inputs.
When executed manually it returns value but not returning any value from
C# code.
create procedure getCustomerID
#firstname CHAR(25),
#lastname CHAR(25),
#middlename as CHAR(25)=null,
#DOB datetime,
#CustomerState as CHAR(25)=null,
#CustomerNumber INTEGER,
#ID nvarchar(25) output
as
begin
....
...
set #ID='something'
end
USE [TestDB]
GO
declare #ID nvarchar(25)
EXECute [dbo].[getCustomerID]
'A', 'B','C','1963-09-06','', 12345, #ID out
print 'ID:'+#ID
GO
OUTPUT
ID: CN0075
C# code:
try
{
using (SqlConnection conn = new SqlConnection("Connectionstring"))
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
using (var command = new SqlCommand("getCustomerID", conn)
{
CommandType = CommandType.StoredProcedure
})
{
command.Parameters.Add("#firstname", SqlDbType.Char, 25).Value = "A";
command.Parameters.Add("#lastname", SqlDbType.Char, 25).Value = "B";
command.Parameters.Add("#middlename", SqlDbType.Char, 25).Value = "C";
command.Parameters.Add("#CustomerState", SqlDbType.Char, 25).Value = "";
command.Parameters.Add("#DOB", SqlDbType.DateTime).Value = "1963-09-06";
command.Parameters.Add("#CustomerNumber", SqlDbType.Int).Value = "12345";
command.Parameters.Add("#ID", SqlDbType.NVarChar, 25).Direction =
ParameterDirection.Output;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string retunID = command.Parameters["#ID"].Value.ToString();
}
}
}
}
}
catch (Exception e)
{
Logger.Error(e.Message);
}
It does not throw exception. It executes the the stored procedure and does
not go inside While(reader.read()) loop and read data.
in your sp use select instate of print
create procedure getCustomerID
#firstname CHAR(25),
#lastname CHAR(25),
#middlename as CHAR(25)=null,
#DOB datetime,
#CustomerState as CHAR(25)=null,
#CustomerNumber INTEGER,
#ID nvarchar(25) output
as
begin
....
...
set #ID='something'
select #ID
end
USE [TestDB]
GO
declare #ID nvarchar(25)
EXECute [dbo].[getCustomerID]
'A', 'B','C','1963-09-06','', 12345, #ID out
select 'ID:'+#ID
GO
enter image description here
I am having an issue with the code below, I keep getting
"Procedure or function 'InsertFile' Expects parameter '#ID', which was
not supplied"
I must be doing something wrong in the returning of the ID.
ALTER PROCEDURE [dbo].[InsertFile]
-- Add the parameters for the stored procedure here
--#AssetID INT,
#ComputerName varchar(max),
#FilePath varchar(max),
#Owner varchar(100),
#Size int,
#Extension varchar(50),
#CreationDate datetime,
#ModifiedDate datetime,
#AccessedDate datetime,
#ID int output
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF NOT EXISTS (SELECT * From DC_Files Where computerName = #ComputerName AND FilePath = #FilePath)
BEGIN
INSERT INTO DC_Files (ComputerName, FilePath, Owner, Size, Extension, CreationDate, ModifiedDate, AccessedDate)
VALUES (#ComputerName, #FilePath, #Owner, #Size, #Extension, #CreationDate, #ModifiedDate, #AccessedDate)
END
ELSE
BEGIN
UPDATE DC_Files
SET Owner = #Owner, Size = #Size, CreationDate = #CreationDate, ModifiedDate = #ModifiedDate, AccessedDate = #AccessedDate
WHERE computerName = #ComputerName AND FilePath = #FilePath
END
SET #ID = SCOPE_IDENTITY()
END
The C# code:
SqlCommand cmd = new SqlCommand("InsertFile",conn);
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue("#AssetID", FileInfo);
cmd.Parameters.AddWithValue("#ComputerName", Environment.MachineName);
cmd.Parameters.AddWithValue("#FilePath", FilePath);
cmd.Parameters.AddWithValue("#Owner", FileSecurity.GetOwner(typeof(NTAccount)).Value);
cmd.Parameters.AddWithValue("#Size", FileInfo.Length);
cmd.Parameters.AddWithValue("#Extension", FileInfo.Extension);
cmd.Parameters.AddWithValue("#CreationDate", FileCreationTime);
cmd.Parameters.AddWithValue("#ModifiedDate", FileModifiedTime);
cmd.Parameters.AddWithValue("#AccessedDate", FileAccessedTime);
var returnParameter = cmd.Parameters.Add("#ID", SqlDbType.Int);
cmd.ExecuteNonQuery();
You have to set the Direction to Output since by default the Direction of all Parameter is Input.
// Create parameter with Direction as Output
SqlParameter returnParameter = new SqlParameter("#ID", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(returnParameter);
Try Adding output parameter as follows in ur C# code
SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = "#ID";
outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
outPutParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outPutParameter);
Procedure or function 'login' expects parameter '#Abc', which was not supplied
4 hours searching and trying and no use I already supplied this parameter (copy/paste) and the number of parameters given to procedure is the same of procedure and in order.
#Abc is an output parameter.
Stored procedure definition:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[login]
(
#Abc int output,
#firstname varchar(255) output,
#lastname varchar(255) output,
#Email varchar(255),
#pass varchar(255)
)
As
begin
if not exists (select Email from user_1 where email=#email)
select #Abc = 0
else begin
if not exists (
select Email from user_1 where email =#Email and password = #pass
)
select #Abc = 1
else
select #Abc = 2,#firstname = u.first_name ,#lastname=u.last_name from user_1 u where u.email = #email
end
end
Code to call the stored procedure:
myCon.Open();
TextBox username = UserName;
TextBox password = Password;
SqlCommand myCommand = new SqlCommand("login", myCon);
SqlParameter count= myCommand.Parameters.Add("#Abc", SqlDbType.Int);
count.Direction = ParameterDirection.Output;
SqlParameter fnp = myCommand.Parameters.Add("#firstname", SqlDbType.VarChar,255);
fnp.Direction = ParameterDirection.Output;
SqlParameter lnp = myCommand.Parameters.Add("#lastname", SqlDbType.VarChar, 255);
lnp.Direction = ParameterDirection.Output;
myCommand.Parameters.AddWithValue("#Email",username.Text);
myCommand.Parameters.AddWithValue("#pass", password.Text);
myCommand.ExecuteNonQuery();
myCon.Close();
You have omitted:
myCommand.CommandType = CommandType.StoredProcedure;
So the command sent to the DB is a malfed sp_executeSQL call instead of the desired exec login
FYI there is also a shorter syntax:
myCommand.Parameters.Add("#Abc", SqlDbType.Int).Direction = ParameterDirection.Output;
I have a stored procedure which returns new ids.
create proc [dbo].[WriteIT]
(#deg nvarchar(max))
as
DECLARE #s nvarchar(max)
set #s = 'INSERT INTO test OUTPUT inserted.ID VALUES '
set #s += #deg
exec (#s)
How can I get that multiple results of stored procedures into a int[]?
string con = "Server=.;Database=Adb;Trusted_Connection=True";
SqlConnection connet = new SqlConnection(con);
SqlCommand cm = new SqlCommand("WriteIT", connet);
cm.CommandType = System.Data.CommandType.StoredProcedure;
bd = new StringBuilder();
string veri = "({0}),";
string sablon = "'{0}','{1}'";
for (int i = 0; i < 50; i++)
{
bd.Append(string.Format(veri, string.Format(sablon, new Random().Next(0, 100000).ToString(), new Random().Next(0, 100000).ToString())));
}
cm.Parameters.AddWithValue("#deger", bd.ToString().Substring(0, bd.Length - 1));
if (connet.State == System.Data.ConnectionState.Closed)
connet.Open();
string a = cm.ExecuteScalar();
ExecuteScalar is meant to return only the first column of the first row from the result..
If your SProc would return more than one value, you could use the ExecureReader() method.
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
You should also read on Random class. You should use the same instance to generate numbers.
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Usp_CRMEntryInsert]
#custnam nvarchar(250),
#proj nvarchar(255),
#projid int,
#contact nvarchar(100),
#updfile nvarchar(150),
#vtype nvarchar(100),
#sts varchar(15),
#recsts varchar(1),
#entryid int,
#entrydate datetime,
#dataentrydate datetime
AS
BEGIN
SET NOCOUNT ON;
insert into CRMEntry (custnam,Proj,projid,contact,updfile,vtype,status,rec_status,entered_id,entered_date,entry_date) values (#custnam,#proj,#projid,#contact,#updfile,#vtype,#sts,#recsts,#entryid,#entrydate,#dataentrydate)
select scope_identity()
This Scope_identity() return max value
maxid = cmd.ExecuteScalar()
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
)