oledb stored procedure c# Procedure or function expects parameter which was not supplied - oledb

I am getting the error : Implicit conversion from data type nvarchar to varbinary is not allowed. Use the CONVERT function to run this query.
my c# code snippet is:
OleDbCommand spCmd = new OleDbCommand
("[SomeServer].[dbo].GetAllProperties", conn)
{
CommandType = CommandType.StoredProcedure
};
spCmd.Parameters.AddWithValue("#P1", path);
spCmd.Parameters.AddWithValue("#P5", 4);
int rowsAffected = spCmd.ExecuteNonQuery();
path is a string.
corresponding sql sp is:
ALTER PROCEDURE [dbo].[GetAllProperties]
#P1 nvarchar (425),
#P2 varchar(32) = NULL,
#P3 as varbinary(85) = NULL,
#P4 as nvarchar(260) = NULL,
#P5 int
AS
BEGIN
....
Please let me know how to invoke this sp from c#.
i tried specifying all parameters in order as follows but then i get error: Implicit conversion from data type nvarchar to varbinary is not allowed. Use the CONVERT function to run this query
spCmd.Parameters.AddWithValue("#P1", path);
spCmd.Parameters.AddWithValue("#P2", DBNull.Value);
spCmd.Parameters.AddWithValue("#P3", DBNull.Value);
spCmd.Parameters.AddWithValue("#P4", DBNull.Value);
spCmd.Parameters.AddWithValue("#P5", 4);
int rowsAffected = spCmd.ExecuteNonQuery();

Default parameters are ONLY used when they are not present, in other words do NOT add them to the parameter list.

to pass null values to the optional parameters simply use null instead of DBType.Null. It works:
spCmd.Parameters.AddWithValue("#P1", path);
spCmd.Parameters.AddWithValue("#P2", null);
spCmd.Parameters.AddWithValue("#P3", null);
spCmd.Parameters.AddWithValue("#P4", null);
spCmd.Parameters.AddWithValue("#P5", 24);

Related

return timestamp value in store procedure

i'm trying to get timestamp value as result of stored procedure.
but getting error .
error message:- SQL Error [100132] [P0000]: JavaScript execution error: Incorrect Timestamp returned.
CREATE OR REPLACE PROCEDURE simple_stored_procedure_example(awesome_argument VARCHAR)
returns TIMESTAMPNTZ
language javascript
as
$$
var cmd = "SELECT EXTRACT_END_TIME FROM EXPLARITY_DB.EXPLARITY_SCHEMA.DEMO_CONTROL_TABLE WHERE PIPELINE_NAME =:1";
var sql = snowflake.createStatement(
{sqlText: cmd,
binds: ['awesome_argument']
}
);
var result1 = sql.execute();
return result1;
$$;
CALL simple_stored_procedure_example('pipeline1');
It can be done like this:
create or replace table tst_tbl(c1 timestamp);
insert into tst_tbl values ('2021-02-02 10:00:00.000');
create or replace procedure my_test(myarg VARCHAR)
returns TIMESTAMP
language javascript
as
$$
var cmd = "SELECT c1 FROM tst_tbl";
var sql = snowflake.createStatement({sqlText: cmd});
var resultSet = sql.execute();
resultSet.next();
my_date = resultSet.getColumnValue(1);
return my_date;
$$;
call my_test('test');
I get 1 row back as expected.

how to call stored procedure in EF6 with output parameters

i have a stored procedure which returns a parameter containing string in it i don't know how to call it and get the output parameter to show on my view
ALTER PROCEDURE [dbo].[sp_test]
#room_type varchar(40)
,#room_price_min float
,#room_price_max float
,#room_number varchar(30)
,#new varchar(50) output
as
;
--select #room_no
if exists(select room_number from Rooms_ms where room_number=#room_number)
begin
set #new='Room Already Exists'
select #new
return
end
insert into Rooms_ms(room_type,room_price_min,room_price_max,room_number) values
(#room_type,#room_price_min,#room_price_max,#room_number)
set #new='Successfully'
select #new
return
I'm trying to catch it like below but don't know how to exactly do it.
var result= db.sp_test(a, b, 0, c);
Thank you
You can implement the following to retrieve the data for a stored procedure call
using(var db = new iConext())
{
var details = db.Database.SqlQuery<iType>("exec iProc #param", new SqlParameter("#param", iValue));
}
iType is int or string or long or can be a ComplexType
#param is one or more required parameters
iContext is for your db connection
It is one of sample my code
string sql = string.Format("exec sp_MyTest '" + methods.DateTimeFormat(vmodel.Search.FDate, false, 1) + "','" + methods.DateTimeFormat(vmodel.Search.TDate, false, 1) + "','" + vmodel.Search.LocationId + "',"+ 0"'");
var result = db.(DbSetName(like.Students))SqlQuery(sql).ToString();
if Return List, then
var result = db.(DbSetName(like.Students))SqlQuery(sql).ToList();

Working with stored procedure in LINQ?

In web application, I am using LINQ to call a procedure, the procedure is parameter procedure. but when I am passing arguments it is giving errors, This is my code:
MyLinqsDataContext DataContext=new MyLinqsDataContext ();
int eno=Convert.ToInt32 (txtempno.Text );
int dep=Convert .ToInt32 (txtDep.Text );
var sqr = from qr in DataContext.USP_Insert_Emp(eno, txtName.Text, dep)
select qr;
But is giving error like:
Could not find an implementation of the query pattern for source type int. Select not found.
This is my Proc :
create procedure USP_Insert_Emp(#empid int,#ename varchar(60),#deptid int)
as
begin
insert into Emp (empid ,ename,deptid ) values (#empid ,#ename ,#deptid)
end
DataContext.USP_Insert_Emp returns an int.
The error you are getting is because you are trying to call Select on an int and not an IEnumerable<T>.

ExecuteStoreQuery with TVP parameters

I have a stored procedure in my database that takes a table value parameter, a list of IdTable objects which contain a single integer Id column.
I have an entity model for the database and want to do the following...
ProjectEntities projectEntities = new ProjectEntities ();
DataTable stationIds = new DataTable();
stationIds.Columns.Add("Id");
stationIds.Rows.Add(1);
stationIds.Rows.Add(2);
SqlParameter parameter = new SqlParameter("#stationIds",stationIds);
parameter.TypeName = "IdTable";
var parameters = new object[] {parameter};
var results = projectEntities .ExecuteStoreQuery<ProjectSummary>("exec ProjectSummary", parameters);
var count = results.Count();
This runs and returns no results, when it should return a bunch of ProjectSummary entities.
When I profile this in SQL Profiler, I get the following
declare #p3 IdTable
insert into #p3 values(N'1')
insert into #p3 values(N'2')
exec sp_executesql N'exec ProjectSummary',N'#stationIds [IdTable] READONLY',#stationIds=#p3
If I declare the stored procedure to be
ALTER PROCEDURE [dbo].[ProjectSummary]
#stationIds [dbo].[IdTable] READONLY
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT * FROM #stationIds
...
Then I get not results back, it looks like the TVP parameter is coming through empty.
Where as if I manually execute
declare #p3 IdTable
insert into #p3 values(N'1')
insert into #p3 values(N'2')
EXEC [ProjectSummary]
#stationIds = #p3
GO
I get the values 1 and 2 returned from the SELECT query.
So, it looks like I want to use EXEC rather than SP_EXECUTESQL when I run ExecuteStoreCommand. Given the code example above, how on earth do I do that?
Turns out the ExecuteStoreQuery call was incorrect, it should be
SqlParameter stations = new SqlParameter { ParameterName = "p0", Value = ids, TypeName = "[dbo].[IdTable]", SqlDbType = SqlDbType.Structured };
var parameters = new object[] { stations };
var results = projectEntities.ExecuteStoreQuery<ProjectSummary>("exec ProjectSummary #p0", parameters);
So I needed to name parameter and add the #p0 to the exec command.

I cannot get the output parameter when use function import by Entity Framework

Here's my SQL Server stored procedure :
ALTER PROCEDURE [dbo].[SearchUser]
(#Text NVARCHAR(100),
#TotalRows INT = 0 OUTPUT)
AS
BEGIN
SELECT #TotalRows=1000
SELECT * from Users
END
And my C# code
using (var context = new TestDBEntities())
{
var outputParameter = new ObjectParameter("TotalRows", typeof(Int32));
context.SearchUser("", outputParameter);
Response.Write(outputParameter.Value);
}
However outputParameter.Value always is null.
Could anybody tell me why?
Output parameters filled by its actual values during the execution of the stored procedure.
But table-valued stored procedure actually get executed only in moment when you're trying to iterate resulting recordset, but not calling a wrapper method.
So, this DOES'T work:
using (var context = new TestDBEntities())
{
var outputParameter = new ObjectParameter("TotalRows", typeof(Int32));
context.SearchUser("", outputParameter);
// Paremeter value is null, because the stored procedure haven't been executed
Response.Write(outputParameter.Value);
}
This DOES:
using (var context = new TestDBEntities())
{
var outputParameter = new ObjectParameter("TotalRows", typeof(Int32));
// Procedure does not executes here, we just receive a reference to the output parameter
var results = context.SearchUser("", outputParameter);
// Forcing procedure execution
results.ToList();
// Parameter has it's actual value
Response.Write(outputParameter.Value);
}
When you're working with stored procedures what don't return any recordset, they execute immediately after a method call, so you have actual value in output parameter.
We had a simular issue due to defered excecution our unit tests failed. In short if you have a stored proc that does NOT return anything you need to be sure to set the response type as 'None' when set as 'None' it will be excecuted when called and not defered.
In case you return anything (E.g. Scalar type of String results) it will excecute it when you use the result even if that .Count() or .ToList() is outside of the method that contains the function call.
So try not to force excecution if not need, when needed it should excecute but be sure to declare it correctly or it might not work.
I have same problem before. The main reason I think that the entities framework has the bug in case the user stored procedure has output parameter and return a result set. For example:
ALTER PROCEDURE [dbo].[SearchTest]
(
#RowTotal INT = 0 OUTPUT,
#RowCount INT = 0 OUTPUT
)
AS
BEGIN
SET NOCOUNT ON
SELECT * FROM SomeThing
SELECT #RowTotal = 1233, #RowCount = 5343
END
However if you change the user stored procedure as following, you can get the output params
ALTER PROCEDURE [dbo].[SearchTest]
(
#RowTotal INT = 0 OUTPUT,
#RowCount INT = 0 OUTPUT
)
AS
BEGIN
SET NOCOUNT ON
SELECT #RowTotal = 1233, #RowCount = 5343
END
You can workaround as following:
ALTER PROCEDURE [dbo].[SearchTest]
AS
BEGIN
DECLARE #RowTotal INT, #RowCount INT
SET NOCOUNT ON
SELECT #RowTotal = 1233, #RowCount = 5343
SELECT #RowTotal AS RowTotal, #RowCount AS RowCount, s.*
FROM SomeThing s
END
If anybody has better solution, please tell me

Resources