how to pass two variables value using linq - asp.net-mvc-3

i am getting error while i am passing two variable value to stored procedure using linq
below is how i have used to pass variables to the linq
Customer objCustomer = DbContext.ExecuteStoreQuery<Customer>
("exec getCustomerDetails {0}{1}", CustomerId, OrderId).AsQueryable().ToList();
below is my stored procedure
create procedure getCustomerDetails
#CustomerId int,
#OrderId int
as
select * from customer c
where c.CustomerId = #CustomerId and c.OrderId = #OrderId
below is the error i get
Message = "Must declare the scalar variable \"#p0#p1\"."
please suggest
thanks,

further to what jackie has stated, I think the issue is down to the fact that there is no space between your parameters. try:
("exec getCustomerDetails {0} {1}", CustomerId, OrderId)
hope this helps

I think you are missing a comma between {0} and {1}...
But why don't you import the stored procedure into your entity model, so that you can call the stored procedure like this:
DbContext.getCustomerDetails(CustomerId, OrderId)

Related

Call stored procedure and register out parameter using JDBC Driver

We have written a stored procedure in Snowflake that inserts values in a table and returns a primary key. I'm trying to call this stored procedure using its JDBC driver.
final Connection connection = getJdbcTemplate().getDataSource().getConnection();
final CallableStatement callableStatement = connection.prepareCall("{call REWARD.sp_issue_reward(?, ?, ?)}");
callableStatement.setLong(1, reward.getClientSeq());
callableStatement.setLong(2, reward.getUserUniqueId());
callableStatement.registerOutParameter(3, Types.INTEGER); // throws SQLFeatureNotSupportedException
callableStatement.executeUpdate();
The connection.prepareCall returns an instance of SnowflakeCallableStatementV1.class. Problem is that this class has the following implementation for registering for output parameter:
/*
The Snowflake database does not accept OUT or INOUT parameters, so the registerOutParameter functions and the get
functions (which get values of OUT parameters) will remain not implemented)
*/
public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
A sample stored procedure definition that is in use:
create or replace procedure sp_issue_reward(CLIENT_SEQ float,
USER_SEQ float)
returns float not null
language javascript
called on null input
volatile
as
$$
var REWARD_ID = 1;
var insertStatement = snowflake.createStatement({
sqlText: "INSERT INTO REWARD.REWARD_CPY ("
+ "reward_seq, "
+ "client_seq, "
+ "user_seq) "
+ "VALUES (?, ?, ?)",
binds: [REWARD_ID, CLIENT_SEQ, USER_SEQ]
})
.execute();
return REWARD_ID;
$$;
How to get an output of a stored procedure using Snowflake JDBC driver?
Results are same with this stored procedure as well:
CREATE or replace PROCEDURE testSp()
RETURNS VARCHAR
LANGUAGE javascript
AS
$$
var rs = "Test"
return rs;
$$;
The problem is here:
callableStatement.executeUpdate();
When you're calling a stored procedure from JDBC, you're not executing an update. You're executing a query even though the SP is doing an update.
The stored procedure will return one row with a single column for the result. You can retrieve it like this:
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("call TEST_JDBC()");
while (rs.next()) {
System.out.println(rs.getString(1));
}
You can of course get more sophisticated than this using prepared statements, but use executeQuery.

Optional parameter in query does not work for db2 but works in oracle

Below query works fine for Oracle database, but for Db2 it throws error sqlcode -417.
I have looked up similar problems but did not get any definitive answer:
#Query(value = "select * from tableName f where (aC is null or f.a_c = aC)", nativeQuery = true)
Page<tablename> findByFilters(String aC, Pageable pageable);
On execution the error code is -417
One way to solve this problem would be to rewrite the query as the following:
select * from tableName f where f.a_c = coalesce(aC, f.a_c)
The form of query above is likely to be accepted. In order to find out the exact reason of the error you get, it is necessary to trace the actual SQL statement passed to Db2.
Another option of solving the problem may be to add the CAST operator, which would define the data type of your parameter:
select * from tableName f where (cast(aC as integer) is null or f.a_c = aC)
This is suggested in the description of the error you get

How to query dataset table on primary key of smallInt using linq C#

Let say I have the following sql table. Customer_id column is a primary key with smallint.
And I am trying to create a linq query, where I want to get all data for customer with id, let say 1.
How to do this.
Already done and not working:
1.
var query = from row in dt.AsEnumerable()
where row.Field<Int32>("customer_id") == Convert.ToInt32(2)
select row;
2.
var query = from row in dt.AsEnumerable()
where row.Field<Int16>("customer_id") == Convert.ToInt16(2)
select row
debug for example 1,2
Syntax error
Exceptions
Why don't you use this:
DataRow needle = hayStack.Tables["Customer"].Rows.Find(2);
Your method should be rewritten as something like this:
private DataRow GetCustomerDetails(Int16 customer_id)
{
return _dt.Tables["Customer"].Rows.Find(customer_id);
}
The calling method would have to check for null beeing returned from the method, since an invalid customer_id would cause Find() tu return null.
Try using short type instead of Int32.

How to replicate in LINQ a SQL query that uses Coalesce to pivot rows into a single column

How can I achieve this functionality from SQL in LINQ?
Here I am getting 3 SP Number to one Contract ID:
DECLARE #Names VARCHAR(8000)
SELECT #Names = COALESCE( #Names + ', ', '') + us.SP_NBR
FROM CAATS_ADMIN.CONTRACT_SP us
WHERE US.CNTRCT_ID='1000038'
You can use the LINQ aggregate function. You will need to retrieve the data in a SELECT to a list of strings through whatever data access mechanism you are using then you use the Aggregate like this:
List<string> source = GetMyData();
var b = source.Aggregate ("",
(current, s)=> string.Concat(current, string.Format("{0},", s)) );
This applies the string concatenation to every item in the sequence to build a single string.

Adding a random Guid column to a Linq to Entities query to grab random records

I've found some articles about using the RandomView view and the GetNewID function to pull back randomized records, but they are using this method with Linq to SQL which allows Functions and Stored Procs to be used with no return value or a scalar return value. From what I understand, a Stored Proc has to been returned as one of the Entity Framework objects from my generated model. I have been able to get that to work as an object, but not returning a scalar or no return set.
What I want to do is to simply add a column to my Linq query that contains a newly generated Guid so that I can order by the new Guids and take a specific number of records randomly. Can anyone help with some sort of lambda expression or join that would enable me to do this? It seems like it should be something built into EF, but I understand that we are on EF v1.
(Please provide code in VB.net)
In the Select clause of your Linq query, you should be able to insert a GUID like this:
var result = from myRecord in myTable
select new {
field1 = myRecord.field1,
field2 = myRecord.field2,
guidField = Guid.NewGuid()
};
Well, my VB is a little rusty, but I think this will work...
Dim result =
From myRecord in myTable _
Select field1, _
field2, _
guidField = System.Guid.NewGuid()

Resources