表值函数参数为varchar

时间:2014-07-07 14:24:41

标签: sql sql-server vb.net sql-server-2008 ado.net

我的SQL Server 2008数据库中有这个表值函数:

Create FUNCTION dbo.fct1(@Code varchar(10) )
RETURNS TABLE
AS
RETURN
(
   select CODE , NOM 
   from CODIF 
   where NUMERO = 'TP'
   and CODE =  @Code 
)

当我从我的代码中调用它时:

 sSQL = "select * from fct1(" & Code & ")"
        Dim cmd As New SqlCommand(sSQL, Connection)
        If Connection.State <> ConnectionState.Open Then Connection.Open()
        Dim rd As SqlClient.SqlDataReader
        rd = cmd.ExecuteReader()

我收到此错误:

  

列名无效:&#39; EA2&#39;

我需要知道:

  • 出现此错误的原因是什么?
  • 我该如何解决?

2 个答案:

答案 0 :(得分:5)

您错过了sql中的'

你应该参数化SQL并尝试使用:

using conn as new sqlconnection(connstring), comm as new sqlcommand("",conn)

    conn.open()

    comm.commandtype = commandtype.text
    comm.commandtext = "select * from fct1(@Code)"
    comm.parameters.addwithvalue("@Code",Code)

    Dim rd as sqldatareader = comm.executedatareader

end using
祝你好运。

答案 1 :(得分:2)

错过'

sSQL = "select * from fct1('" & Code & "')"
        Dim cmd As New SqlCommand(sSQL, Connection)
        If Connection.State <> ConnectionState.Open Then Connection.Open()
        Dim rd As SqlClient.SqlDataReader
        rd = cmd.ExecuteReader()