我有一个存储过程:-
ALTER PROCEDURE [dbo].[Usp_GetFilterDM]
-- Add the parameters for the stored procedure here
@shortid nvarchar(10),
@dmno nvarchar(10),
@LOB int,
@Status int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @sqlCommand nvarchar(1000)
SET @sqlCommand ='SELECT * FROM [ProjectTracker].[dbo].[View_GetALLDM] where (status <> 1 and status <> 2) '
IF @shortid <>'NO'
SET @sqlCommand = @sqlCommand + 'and shortid LIKE ''%'+ @shortid +'%'''
IF @dmno <>'NO'
SET @sqlCommand = @sqlCommand + 'and DMNO LIKE ''%'+@dmno+'%'''
IF @LOB<> -1
SET @sqlCommand = @sqlCommand + 'and LOB = @LOB '
IF @Status <> -1
SET @sqlCommand = @sqlCommand + 'and Status = @Status'
EXEC sp_executesql @sqlCommand, N' @LOB INT,@Status int', @LOB,@Status;
END
当我直接执行它时,我会得到值,但是当我使用ado .net模型在我的C#代码中使用它并像这样调用它时:-
var x = obj.Usp_GetFilterDM(shortid,dmno,LOB,status);
var userDataString = JsonConvert.SerializeObject(x);
return userDataString;
在所有情况下,我的输出均为-1,我对所有查询都使用了存储过程,并且一切正常,但这是我第一次使用动态生成查询和sp_executeSQL。通常,我只会写一个选择查询,它总是可以工作。
USP_GetFilterDM下的代码:-
public virtual int Usp_GetFilterDM(string shortid, string dmno, Nullable<int> lOB, Nullable<int> status)
{
var shortidParameter = shortid != null ?
new ObjectParameter("shortid", shortid) :
new ObjectParameter("shortid", typeof(string));
var dmnoParameter = dmno != null ?
new ObjectParameter("dmno", dmno) :
new ObjectParameter("dmno", typeof(string));
var lOBParameter = lOB.HasValue ?
new ObjectParameter("LOB", lOB) :
new ObjectParameter("LOB", typeof(int));
var statusParameter = status.HasValue ?
new ObjectParameter("Status", status) :
new ObjectParameter("Status", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("Usp_GetFilterDM", shortidParameter, dmnoParameter, lOBParameter, statusParameter);
}