如何在SQL参数太长的时候传入它

时间:2011-11-17 15:23:18

标签: .net sql-server-2008

我有一个非常大的'Where'语句,它比允许的最大值更长。

目前我在vb.net代码中构建完整的sql并执行它。

问题是这种方式很慢,因为它不是编译的查询。

还有其他办法吗?

编辑:

  For i As Integer = 0 To List.Count - 1
        If Filter = String.Empty Then
            Filter = " Where OrderID = "
        Else
            Filter += " OR OrderID ="
        End If
        Filter = Filter + "(" & List(i) + ")"
    Next

    Sql = "Select * from OrderPickSheet " & Filter & " And Status > -1 Order by SortOrder"
    cmd.CommandText = Sql
    cmd.ExecuteReader()

3 个答案:

答案 0 :(得分:2)

您可以调用存储过程并在DataTable中传递值,而不是在客户端上构造SQL语句。在您的存储过程中,加入传入的值,这意味着您不需要构建长动态sql语句,并降低sql注入攻击的风险。

例如,如果您在数据库中创建此类型和过程(我在这里猜测数据类型):

create type dbo.OrderIdInfo as table
(
    OrderId nvarchar(20)
)

create procedure dbo.SelectOrders
(
    @orderIds dbo.OrderIdInfo readonly
)
as

    select o.* 
    from OrderPickSheet o
        inner join @orderIds i on o.OrderId = i.OrderId
    where o.Status > -1
    order by o.SortOrder

您可以按如下所示调用该过程。代码运行(在LINQPad中测试),但VB不是我的主要语言,所以原谅任何笨拙:

Dim table As New DataTable
Dim results As New DataTable

table.Columns.Add("OrderId", GetType(String))

table.Rows.Add("1")
table.Rows.Add("2")
table.Rows.Add("4")

Dim parameter As New SqlParameter("@orderIds", SqlDbType.Structured)

parameter.Value = table

Using connection As SqlConnection = New SqlConnection("server=localhost;database=Test;integrated security=true")
    Using command As SqlCommand = connection.CreateCommand()

        command.CommandText = "dbo.SelectOrders"
        command.CommandType = CommandType.StoredProcedure
        command.Parameters.Add(parameter)

        connection.Open()

        Dim reader As SqlDataReader = command.ExecuteReader()

        results.Load(reader)

    End Using
End Using

答案 1 :(得分:1)

您可以在存储过程中而不是在.NET中动态创建SQL。

查询仍然无法编译,但您可以通过逗号分隔的字符串或XML传递所有变量

答案 2 :(得分:1)

通过动态构建一组参数,您可以在SQL命令中保存相当长的时间(并保护自己免受SQL注入攻击,启动):

    Dim paramList As New StringBuilder
    For i As Integer = 0 To List.Count - 1
        Dim paramName As String = String.Format("@p{0}", i)
        If paramList.Length > 0 Then
            paramList.Append(",")
        End If
        paramList.Append(String.Format(paramName))
        cmd.Parameters.AddWithValue(paramName, List(i))
    Next
    cmd.CommandText = "Select * from OrderPickSheet Where OrderID in (" & paramList.ToString() & ") And Status > -1 Order by SortOrder"
    cmd.ExecuteReader()