SQLServerCE来自.NET的参数化查询的问题

时间:2009-12-02 21:42:17

标签: .net sql-server-ce parameterized-query

我正在把头发拉出脑袋试图弄清楚这个。

当我使用参数时,我无法使参数化查询在VB.Net中工作。

根据我的发现,在.NET中使用函数中的参数会引发错误(请参阅示例代码)。但是,在Visual Studio的“查询窗口”中运行不起作用的查询可以正常工作。

引发的错误是:

  

25922 - 函数的参数无效。

来自的信息: http://msdn.microsoft.com/en-us/library/aa256772%28SQL.80%29.aspx

示例代码:

Imports System.Data.SqlServerCe

Public Class MiniDemo

    Public Shared Sub Main()
        Dim cs As String = "Data Source=Inventory.sdf; Persist Security Info=False;"
        Dim db As New SqlCeConnection(cs)
        db.Open()


        ''#Using parameters works
        Dim cmd As SqlCeCommand = db.CreateCommand()

        cmd.CommandText = "INSERT INTO inventory_type (inv_type_id, inv_type_name) VALUES (@id, @name)"
        cmd.Parameters.Add("@id", 1)
        cmd.Parameters.Add("@name", "test")
        cmd.ExecuteNonQuery()



        ''#Using parameters in functions does not work
        Dim cmd2 As SqlCeCommand = db.CreateCommand()

            ''#Broken on multiple lines for readability (built using string builders in real code)
        cmd2.CommandText = 
                     "SELECT 
                        inv_type_id, 
                        inv_type_name 
                      FROM
                        inventory_type 
                      WHERE 
                        ((@id IS NULL) OR (inv_type_id = @id)) AND 
                        ((@name IS NULL) OR (inv_type_name = @name))"

        cmd2.Parameters.Add("@id", 1)
        cmd2.Parameters.Add("@name", "test") ''# Would not work with DBNull.Value either

        Dim da2 As New SqlCeDataAdapter(cmd2)
        Dim dt2 As New DataTable()
        da2.Fill(dt2)
        db.Close()
    End Sub

End Class

1 个答案:

答案 0 :(得分:4)

最后,我找到了解决这个问题的方法。

如果未设置参数的DBType属性,则在函数中使用参数会崩溃:

这会崩溃:

    Dim cmd As SqlCeCommand = db.CreateCommand()

    cmd.CommandText = "SELECT COALESCE(@param1, @param2);"
    cmd.Parameters.Add("@param1", 1)
    cmd.Parameters.Add("@param2", "test")
    cmd.ExecuteScalar()

如果参数的DBType属性设置

,则在函数中使用参数将起作用

这样可行:

    Dim cmd As SqlCeCommand = db.CreateCommand()

    cmd.CommandText = "SELECT COALESCE(@param1, @param2);"
    cmd.Parameters.Add("@param1", 1).DbType = DbType.Int32
    cmd.Parameters.Add("@param2", "test").DbType = DbType.String
    cmd.ExecuteScalar()