在做一个小项目的时候遇到一个很纠结的问题。这里和大家分享一下 ,希望对有同样问题的朋友有所帮助
问题:有如下一个复杂查询
在三层架构中这是一个让人很纠结的问题,最终觉得把界面层所有参数都封装到一个实体类中,传递三个实体类作参数,
''' <summary>
''' 组合查询条件实体
''' </summary>
Public Class Condition
''' <summary>
''' 字段名
''' </summary>
Private m_FileName As String
''' <summary>
''' 操作符
''' </summary>
Private m_Operate As String
''' <summary>
''' 字段值
''' </summary>
Private m_FileValue As String
''' <summary>
''' 关系符
''' </summary>
Private m_Relation As String
''' <summary>
''' 字段名
''' </summary>
Public Property FileName() As String
Get
Return m_FileName
End Get
Set(ByVal Value As String)
m_FileName = Value
End Set
End Property
''' <summary>
''' 操作符
''' </summary>
Public Property Operate() As String
Get
Return m_Operate
End Get
Set(ByVal Value As String)
m_Operate = Value
End Set
End Property
''' <summary>
''' 关系符
''' </summary>
Public Property Relation() As String
Get
Return m_Relation
End Get
Set(ByVal Value As String)
m_Relation = Value
End Set
End Property
''' <summary>
''' 字段值
''' </summary>
Public Property FileValue() As String
Get
Return m_FileValue
End Get
Set(ByVal Value As String)
m_FileValue = Value
End Set
End Property
End Class ' Condition
紧接着又有一个问题,想把sql语句查询写成存储过程,一路坎坷,一些单引号,空格 很多小的问题很让人头疼,这里把最终的解决方案分享一下。
ALTER PROCEDURE [dbo].[proc_Condition_Query]
@FileName1 varchar(10), @Operator1 varchar(1),@FileValue1 varchar(10),@Relation1 varchar(10),
@FileName2 varchar(10), @Operator2 varchar(1),@FileValue2 varchar(10),@Relation2 varchar(10),
@FileName3 varchar(10), @Operator3 varchar(1),@FileValue3 varchar(10),@InfoName varchar(10) 表的名称
AS
DECLARE @TempSql varchar(500) --临时存放sql语句
BEGIN
set @TempSql= 'select * from '+@InfoName+' where ' + @FileName1 + @Operator1 + char(39)+ @FileValue2+char(39)--拼接sql字符串,单引号用Assci值替代
if (@Relation1 is not null)
begin
if (@Relation2 is null)
begin
set @TempSql =@TempSql+space(1)+@Relation1+space(1)+@FileName2+space(1)+@Operator2+space(1) +char(39)+ @FileValue2+char(39)--操作符两侧的空格用Space(1) 解决
end
else
begin
set @TempSql =@TempSql+space(1)+@Relation1+space(1)+ @FileName2+space(1)+@Operator2+space(1) +char(39)+ @FileValue2+char(39)+space(1)+@Relation2+space(1)+ @FileName3+space(1)+@Operator3+space(1) +char(39)+ @FileValue3+char(39)
end
end
exec(@TempSql)
END
总结问题:其中不加单引号会出现以下问题