我有一个ASP.NET 2010应用程序命中SQL 2005数据库。我正在尝试动态构建存储过程,具体取决于在搜索屏幕上选择的值。我已经在.net&的previosu版本中多次这样做了。 sql没问题。但是,现在,我的IF语句始终表现得好像没有传入数据。我已经调试了应用程序,并确保正在设置数据。我应该注意,当我直接运行程序时,无论是否有数据,都会返回正确的数据。
这是一个相当简单的存储过程..
ALTER PROCEDURE get_cases_by_search_criteria
@vin as varchar(30) = null
AS
declare @sqlstr varchar(1000)
set @sqlstr = 'SELECT
[Case].CaseID,
[Case].VIN,
[Case].Make,
[Case].Model,
[Case].VehicleYear,
if @vin is not null and @vin <> ''
set @sqlstr = @sqlstr + ' and ' + ('[Case].VIN = ''' + convert(varchar,@vin) + '''')
exec(@sqlstr)
RETURN
以下是调用存储过程的代码...
Public Function GetCases(ByVal oSearchCriteria As SearchCriteria) As List(Of BE.Case)
Dim lstCase As New List(Of BE.Case)
Dim oCase As BE.Case
Dim oProviderFactory As New ProviderFactory
Dim oConnection As DbConnection
Dim oReader As System.Data.IDataReader
Dim oFactory As DbProviderFactory
Dim oCmd As DbCommand
Dim param1 As System.Data.Common.DbParameter
Try
'call my class to get an instance of the DBProviderFactory class
oFactory = oProviderFactory.GetFactory
'call another class of mine. pass in the DBProviderFactory class which will create a non-provider-specific connection object
oConnection = oProviderFactory.GetProviderConnection(oFactory)
'non-specific create command
oCmd = oConnection.CreateCommand
'non-specific parameter
If oSearchCriteria.VIN.Length = 0 Then
param1 = oFactory.CreateParameter()
param1.ParameterName = "@vin"
param1.DbType = DbType.String
param1.Value = DBNull.Value
oCmd.Parameters.Add(param1)
Else
param1 = oFactory.CreateParameter()
param1.ParameterName = "@vin"
param1.DbType = DbType.String
param1.Value = oSearchCriteria.VIN
oCmd.Parameters.Add(param1)
End If
oCmd.CommandType = CommandType.StoredProcedure
oCmd.CommandText = "get_cases_by_search_criteria"
Using (oConnection)
oConnection.Open()
oReader = oCmd.ExecuteReader()
While oReader.Read
oCase = New BE.Case
'Case
If oReader("CaseID") IsNot System.DBNull.Value Then oCase.CaseID = oReader("CaseID")
If oReader("Make") IsNot System.DBNull.Value Then oCase.Make = oReader("Make")
If oReader("Model") IsNot System.DBNull.Value Then oCase.Model = oReader("Model")
If oReader("VehicleYear") IsNot System.DBNull.Value Then oCase.VehicleYear = oReader("VehicleYear")
If oReader("VIN") IsNot System.DBNull.Value Then oCase.VIN = oReader("VIN")
lstCase.Add(oCase)
End While
oConnection.Close()
End Using
Catch ex As Exception
Throw ex
End Try
Return lstCase
End Function