且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用ADO和VB将NULL或空字符串传递给存储过程输入参数?

更新时间:2023-10-31 15:41:34

A这里的快速测试表明NULL应该可以完成工作。我曾经测试的示例代码(到一个带有一个按钮和一个文本框的简单表单中):

A quick test here shows that's NULL ought to do the job. Sample code I used to test (onto a simple form with one button and one textbox):

Private Sub Command1_Click()
    Dim dbConn As ADODB.Connection
    Dim dbComm As ADODB.Command
    Dim dbRS As ADODB.Recordset

    Set dbConn = New ADODB.Connection
    With dbConn
        .ConnectionString = "...REPLACE THIS ACCORDINGLY..."
        .ConnectionTimeout = 10
        .Open
    End With
    Set dbComm = New ADODB.Command
    With dbComm
        .ActiveConnection = dbConn
        .CommandType = adCmdStoredProc
        .CommandText = "usp_Bob"
        .Parameters.Append .CreateParameter("b", adVarChar, adParamInput, 10, Null)
        Set dbRS = .Execute
    End With
    Text1.Text = dbRS.Fields.Item(0).Value

    dbRS.Close
    dbConn.Close
End Sub

它调用了此存储过程:

ALTER PROCEDURE usp_Bob
 @b VARCHAR(10)
AS
 IF @b IS NULL
  SELECT 'NULL' AS '1'
 ELSE
  IF @b = ''
   SELECT 'EMPTY' AS '1'
  ELSE
   SELECT 'NOT NULL AND NOT EMPTY' AS '1'

usp_Bob由于使用VB值 Null (根据上面的示例)而返回'NULL',而'NOT' vbNull 为NULL。如果 Null 对您不起作用,那么我无法评论可能是什么问题...!

usp_Bob returned 'NULL' for using the VB value Null (as per the sample above), and 'NOT NULL' for vbNull. If Null doesn't work for you, then I can't comment on what might be wrong...!

类似地,应该像这样传递空字符串-一个空字符串,即 str = -这会使usp_Bob返回'EMPTY'。

Similarly, empty strings should be passed just as that -- an empty string, i.e. str = "" -- which makes usp_Bob return 'EMPTY'. Anything else has it return 'NOT NULL AND NOT EMPTY' (as expected).

如果您无法通过NULL,那么另一种选择是将其强制转换为空。在程序中将字符串转换为NULL-即

If you can't get NULL passed through, then another option is to cast an empty string to NULL in the sproc -- i.e.,

IF @param = ''
    SET @param = NULL

请注意,经过的长度并不太重要。这反映了SQL Server中定义的参数的最大长度,而不是您正在传递的数据的长度。

Note that the length you pass through shouldn't matter too much. It's a reflection of the maximum length of the parameter as defined in SQL Server rather than the length of the data you're passing through.