How to pass NULL or empty strings to stored procedure input parameter with ADO and VB?

后端 未结 3 626
既然无缘
既然无缘 2021-01-05 03:22

I have a stored procedure in Sql Server 2005 with a varchar input parameter defined as:

@Value varchar(24) = NULL

in my VB6 application I t

3条回答
  •  走了就别回头了
    2021-01-05 03:45

    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
    

    And it called this stored proc:

    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 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...!

    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).

    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
    

    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.

提交回复
热议问题