passing NVARCHAR value to stored procedure - c#

I have a stored procedure with NVARCHAR parameter like this:
ALTER PROCEDURE [dbo].[hr_Companies_GetByIDAndName]
#CompanyName NVARCHAR(100),
#Lang int = 1
AS
Select * from companies
where
(#Lang = 1 AND NameLang1 LIKE #CompanyName )
OR
(#Lang = 2 AND NameLang2 LIKE #CompanyName )
)
I want to supply it a nvarchar value so I am using this syntax:
DBHelper _helper = new DBHelper();
_helper.StoredProc = "hr_Companies_GetByIDAndName";
_helper.AddParam("#CompanyName", "N'%" + company.Trim() + "%'", SqlDbType.NVarChar);
_helper.AddParam("#Lang", Language, SqlDbType.Int);
return _helper.GetTable();
But it is returning null.
When I run query without stored procedure select * from companies where companyname like N'%mycompanyname%', it returns result.
How to add N using DBHelper addparameter?

I'm not sure what your DBHelper does but to pass nvarchar type values to stored procs, following is the standard way:
var param = new SqlParameter("#CompanyName ", SqlDbType.NVarChar, size)
param.Value = company.Trim();
The 3rd parameter above is size of nvarchar parameter that is declared in sproc using nvarchar(size) syntax. If it is nvarchar(max) then use -1.
Also note that you don't need to use "N %" prefix. ADO.Net layer takes care of it.

Related

How to pass in parameters for in clause that is in a stored procedure?

How would I take this query that is in my stored procedure and pass in the correct parameters?
select * from Inventory
where category in (#categories) and qty > #qty and condition in (#conditions)
I seen that I should do something like this
CREATE PROCEDURE [dbo].[usp_DoSomethingWithTableTypedParameter]
(
#categories categories READONLY
#Qty int,
#conditions
)
But how does the ADO.NET side look like? If I were to pass in for categories 'Tools', 'Hardware' and for conditions 'New', 'Used'.
How would I do this?
To add 3 further parameters to your SP, #Qty, #Category & #Condition you just duplicate the steps you've already taken.
Create any additional User Defined Table Types
Both #Category and #Condition need a UDT, #Qty doesn't as it is a native type.
Some people will prefer having a separate UDT each for #Category and #Condition, personally given they both take the same datatype I create a single general purpose utility UDT e.g.
CREATE TYPE [dbo].[udt_ShortString] AS TABLE
(
[Value] [varchar](128) NULL
)
Modify the SP e.g.
CREATE PROCEDURE [dbo].[usp_DoSomethingWithTableTypedParameter]
(
#UserIdList udt_UserId READONLY
, #CategoryList udt_ShortString READONLY
, #ConditionList udt_ShortString READONLY
, #Qty int
)
AS
Add the values to your command object, where you load the new datatables exactly the same as you are already loading your existing userId table e.g.
cmd.Parameters.Add(new SqlParameter("#UserIdList", System.Data.SqlDbType.Structured) { TypeName = "udt_UserId", Value = userIdList });
cmd.Parameters.Add(new SqlParameter("#CategoryList", System.Data.SqlDbType.Structured) { TypeName = "udt_ShortString", Value = categoryList });
cmd.Parameters.Add(new SqlParameter("#ConditionList", System.Data.SqlDbType.Structured) { TypeName = "udt_ShortString", Value = conditionList });
cmd.Parameters.Add(new SqlParameter("#Qty", SqlDbType.Int) { Value = qty });
Note: For clarity I have hardcoded the parameter names and type names in - you are of course free to pass them as variabled as you were doing.

How to return list item as JSON in ASP.NET MVC using stored procedure result?

I want to return some data from a SQL Server table; I used a stored procedure like this:
ALTER PROCEDURE [dbo].[SP_TITILESEARCH]
(#FLAG INT,
#Author VARCHAR(300) = NULL,
#Category VARCHAR(100) = NULL,
#Title VARCHAR(MAX) = NUll)
AS
BEGIN
IF (#FLAG = 1)
BEGIN
SELECT *
FROM SmartLibClientDB.dbo.LibraryMediaEntry
WHERE Title LIKE '%' + #Title + '%'
END
END
On the server-side, the stored procedure is executed like this:
var media = new LibraryMediaEntry();
var db = new SchooberrySchoolEntities();
SqlParameter param1 = new SqlParameter("#Title", "Charpy Impact Test");
SqlParameter param2 = new SqlParameter("#FLAG", 1);
media = db.Database.SqlQuery<LibraryMediaEntry>("exec SP_TITILESEARCH #Title, #FLAG", param1, param2)
.ToList()
.FirstOrDefault(); // Getting error when executed
return Json(media, JsonRequestBehavior.AllowGet);
But the code throws an error:
Conversion failed when converting the varchar value 'Charpy Impact Test' to data type int.
What I want to do is return the table data as JSON is this the correct method to do this? Or why the error? I can't understand what I am doing wrong because the column the error asking to convert to int is actually a varchar column
Note: I am using a stored procedure because the data I am returning is from a different database on the same server
Conversion failed when converting the varchar value 'Charpy Impact Test' to data type int.
This means that the #Title parameter is expecting an int (integer). Charpy Impact Test is not an integer so your stored procedure call fails. Picking an integer value is the first step.
want to do is return the table data as JSON
Your code:
media = db.Database.SqlQuery<LibraryMediaEntry>("exec SP_TITILESEARCH #Title,#FLAG"
,param1
,param2)
.ToList()
.FirstOrDefault();
is calling .FirstOrDefault() which will result in a singe row in media. Did you intend to have a single record returned?
There are a couple of possible issues with your code.
Your stored proc param #FLAG is defined as varchar(25). Yet, when populating it, you are passing an integer (SqlParameter param2 = new SqlParameter("#FLAG",1);). Change it to:
var param2 = new SqlParameter("#FLAG", "1");
On the matter of the actual error you are getting... Check your LibraryMediaEntry object. Is the property that's getting populated an int by any chance? That's probably where the problem lies.
Finally, your stored proc. SELECT * FROM is bad form in a stored procedure. Specify the actual fields you want. It also helps with debugging.
I couldn't find what caused the error but passing all parameters including the null did the job for me
var DB = new dbEntities();
SqlParameter param1 = new SqlParameter("#FLAG", 1);
SqlParameter param2 = new SqlParameter("#Author", "");
SqlParameter Param3 = new SqlParameter("#Category", "");
SqlParameter param4 = new SqlParameter("#Title", Convert.ToString(id));
var medias = db.Database.SqlQuery<LibraryMediaEntry>("exec SP_TITILESEARCH #FLAG,#Author,#Category,#Title", param1, param2, Param3, param4).ToList();

Retrieving Issue regarding stored procedures data type

I have written a stored procedure
Then I have written C# code
ds.Tables[0].Rows[0][0].ToString().Split(',')
ds is my dataset which contains stored procedure retrieved from above ImportData (Column SQLQueryName))
The question is: I used string array for strMendetory and I need to find out data type of parameter of stored procedure from strMendetory. When I implement code for the same it returns System.string as usual (even it contains DATETIME).
Please give me suggestion on the same.
Stored procedure code:
CREATE PROCEDURE AddDepartments
#DepartmentName VARCHAR(100),
#DepartmentCode VARCHAR(100),
#CompanyLocationID INT,
#Details VARCHAR(100),
#Flag BIT,
#CreatedDateTime DATETIME,
#MarkDeleted BIT,
#AccessGroupMasterID INT
AS
BEGIN
INSERT INTO Departments(DepartmentName, DepartmentCode, CompanyLocationID,
Details, Flag, CreatedDateTime, MarkDeleted,
AccessGroupMasterID)
VALUES(#DepartmentName, #DepartmentCode, #CompanyLocationID,
#Details, #Flag, #CreatedDateTime, #MarkDeleted,
#AccessGroupMasterID)
END
GO
INSERT INTO ImportData(ImportItemName, ReferenceTableName, ImportFileName,
SQLQueryTypeID, SQLQueryName, MarkDeleted)
VALUES('Department', 'Departments', 'ImportDepartments.xls',
2, 'AddDepartments, #DepartmentName, #DepartmentCode, #CompanyLocationID, #Details, #Flag, #CreatedDateTime, #MarkDeleted, #AccessGroupMasterID', 0)
GO
C# code:
String[] strMendetory = ds.Tables[0].Rows[0][0].ToString().Split(',');
string columnValue="MynewValuToInsertinProcedure";
for (int columCounter = 1; columCounter < strMendetory.Count(); columCounter++)
{
cmd.Parameters.AddWithValue(strMendetory[columCounter], columnValue);
}
Use sqlparameter, you can specify the sql datatype. Here's the code example :
SqlParameter[] param = {
new SqlParameter("#param1", SqlDbType.VarChar, 100),
new SqlParameter("#param2", SqlDbType.Int),
new SqlParameter("#param3", SqlDbType.DateTime)
};
//#param1, #param2, #param3 should match your parameters name in stored procedure
param[0].Value = "test"; //pass the value to your parameter here
param[1].Value = 2;
param[2].Value = DateTime.Now;
SqlCommand sqlcmd = new SqlCommand();
foreach (SqlParameter x in param)
{
sqlcmd.Parameters.Add(x);
}

Entity Framework: how do I run a stored procedure and return a value?

Is it possible to execute a stored procedure using the Entity Framework, passing in variables and returning data along with a return value?
Please do not leave any code about function mappings with Entity Framework.
I have tried this and I keep getting the same damn error:
Procedure or function 'usp_BusinessUser_Search' expects parameter
'#TotalRecords', which was not supplied.
Here's my code:
SqlParameter Business = new SqlParameter("Business", Search.Term);
SqlParameter Location = new SqlParameter("Location", Search.Location);
SqlParameter PageNumber = new SqlParameter("PageNumber", Search.CurrentPage);
SqlParameter RecordsPerPage = new SqlParameter("RecordsPerPage", Search.RecordsPerPage);
SqlParameter TotalRecords = new SqlParameter("TotalRecords", 0);
SqlParameter parm = new SqlParameter()
{
ParameterName = "#TotalRecords",
Value = 0,
SqlDbType = SqlDbType.Int,
Direction = System.Data.ParameterDirection.Output
};
var List = db.ExecuteStoreQuery<ENT_SearchBusinessResult>("exec usp_BusinessUser_Search",Business,Location,PageNumber,RecordsPerPage,parm);
Does anyone have any idea what is causing this?
Thanks
EDIT:
Stored procedure code:
ALTER PROCEDURE [dbo].[usp_BusinessUser_Search] ( #Business nVarChar(255) = NULL
, #Location nVarChar(255) = NULL
, #PageNumber Int = 1
, #RecordsPerPage Int = 10
, #TotalRecords Int OUTPUT)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL NVARCHAR(MAX)
, #CacheTable SYSNAME
, #TotalRows Int
, #Category VarChar(255)
, #BusinessCategory Int
, #TownCounty VarChar(50)
, #PcodeTownCounty VarChar(50)
INSERT Voucher_SearchHistory (Keyword, Location)
SELECT NULLIF(#Business,''), NULLIF(#Location,'')
This might help:
http://blogs.msdn.com/b/diego/archive/2012/01/10/how-to-execute-stored-procedures-sqlquery-in-the-dbcontext-api.aspx
You are not passing TotalRecords Sql Parameter in Excecute
var List = db.ExecuteStoreQuery<ENT_SearchBusinessResult>(
"exec usp_BusinessUser_Search",Business,
Location,PageNumber,RecordsPerPage,parm);
You can now use the following extension method, ExecuteSqlCommandWithReturn, that takes care of all of the work for you!
https://gist.github.com/copernicus365/7037320
string sql = "EXEC sp_CoolProc #SomeParam, #AnotherParam";
int returnValue;
int val = db.ExecuteSqlCommandWithReturn(sql, out returnValue, someParam, anotherParam);
The key to the solution was by Jieyang Hu here, which is this (though note that all of the following is fully handled by the aforementioned extension method): Just as you can do in a SQL prompt, you just set the result of the executed procedure to a SQL variable (in this case which is sent in as a parameter), like this:
EXEC #ReturnVal = sp_MyCoolProc;
This code adds the fragment #ReturnVal = after the first EXEC (followed by whitespace) it finds, and adds to the SqlParameters (or creates SqlParamters if there were none) a ReturnVal parameter, though the caller will never see these.
The parameter name should not contain #:
SqlParameter parm = new SqlParameter()
{
ParameterName = "TotalRecords",
Value = 0,
SqlDbType = SqlDbType.Int,
Direction = System.Data.ParameterDirection.Output
};
If you just added that parameter ('#TotalRecords) recently
I am going to guess that you just need to update your function import definition in your edmx model.

How to do Sql server procedure using parameters like where #para1 = #para2

I have a procedure with a single select statement. I am need to create some 50 procedures like the one below..
create procedure foo1 as
select cityid, cityname from footballteam
the footballteam will be common in all my procedures, Instead of creating 50 single procedures, I want to code like below and send 3 parameters from my c# page
create procedure foo1 (#id bigint, #name varchar(50), #param bigint)as
select #id, #name from footballtem where #id =#param
can i pass like this in sql server ?/ How to do like this
will I am able to do procedure overloading in sql server, some time I need to pass only two parameters and i want to get a particular value , I will pass three or more parameters ....
For a pure TSQL answer:
create table footballtem(id int identity(1,1),cityid int, cityname varchar(50))
go
insert footballtem(cityid, cityname) values (123, 'abc')
insert footballtem(cityid, cityname) values (456, 'def')
go
create procedure foo1 (#id sysname, #name sysname, #param bigint) as
declare #sql nvarchar(100) = 'select ' + QUOTENAME(#id) + ','
+ QUOTENAME(#name) + ' from footballtem where '
+ QUOTENAME(#id) + '=#param'
exec sp_ExecuteSql #sql, N'#param bigint', #param
go
exec foo1 'cityid','cityname',123
(credit is due to Mikael Eriksson re QUOTENAME)
Note that QUOTENAME makes the #name and #id injection safe.
Note also, though, that the varying parameter (#param) is safe from injection - we don't need to validate that anywhere; and that this will allow query-plan re-use via sp_ExecuteSql
No; that would do a comparison on the parameter values, and return the parameter values. To do that, you would have to substitute the values at the caller, for example:
string idColumn = "id", nameColumn = "name";
string tsql = string.Format(#"
create procedure foo1 (#param bigint)
as select [{0}], [{1}] from footballtem where [{0}]=#param", idColumn,nameColumn);
and have 50 SPs; you can do the same in TSQL, using sp_ExecuteSQL against an already replaced string, but IMO it would be better to do this at the app tier than inside the database.
Also; question whether you really need stored procedures... that one isn't really going to help much; a parameterised TSQL query is much simpler, just as fast, and easier to deploy.
I'm not sure if I understand you correctly, but you can specify a default value for a stored procedure parameter in T-SQL. So you can omit it while calling.
CREATE PROCEDURE Proc1 #param1 int, #param2 int = -1 AS SELECT case when #param2=-1 then somefield else #param2 end as column from sometable where somekeyfield=#param1; GO
(assuming MS SQL Server)
MS SQL server does not support procedure overloading (as Oracle Does) but does support input and output parameters like this:
create procedure foo1 (
#param bigint
, #id bigint out
, #name varchar(50) out
)as
select
#id = fbt.id
,#name = fbt.name
from
footballteam fbt
where fbt.id =#param
#id and #name have to be passed in as null value output paramters of the correct type. After execution (cmd.executeNonQuery) you can inspect the command object to get the new parameter values back out.
I am not sure I am reading your question correctly, but if I am then this should get what you want..
*Adding better code sample after question *
//_assumes the following using statements at the top of code file:_
//using System.Data;
//using System.Data.SqlClient;
public string getTeam(int CityID)
{
string name;
using (var cmd = new SqlCommand("foo1",new SqlConnection("myConnectionStringGoesHere")))
{
cmd.Parameters.Add(new SqlParameter("#param", CityID));
cmd.Parameters.Add(new SqlParameter("#id", SqlDbType.BigInt){Direction=ParameterDirection.Output});
cmd.Parameters.Add(new SqlParameter("#name", SqlDbType.VarChar,50) { Direction = ParameterDirection.Output });
cmd.Connection.Open();
cmd.ExecuteNonQuery();
name = cmd.Parameters["#name"].Value.ToString();
cmd.Connection.Close();
}
return name;
}
I think you were asking for the following:
create procedure foo1 (#id bitint out, #name bigint out, #param bigint)
as
select #id=cityid, #name=cityname from footballteam where teamname = #param
But your question makes it seem like you are trying to dynamically change the column names per query.
There is a way to do overloading on MSSQL. Here how it goes:
For example we have a sp_Personel procedure which takes personel type as parameter and lists personel of that type.
CREATE PROCEDURE [dbo].[sp_Personel]
#PersonelType int
AS
SELECT Name, JoinDate, PersonelType, Salary
FROM Personel
WHERE PersonelType = #PersonelType
END
Now, you want another procedure which will be for personel join dates.
CREATE PROCEDURE [dbo].[sp_Personel];2
#JoinDate datetime
AS
SELECT Name, JoinDate, PersonelType, Salary
FROM Personel
WHERE JoinDate <= #JoinDate
END
To call second procedure from management studio;
[dbo].[sp_Personel];2 N'9/26/2010'

Categories