【问题标题】:Returning boolean from SQL Server in VB.NET从 VB.NET 中的 SQL Server 返回布尔值
【发布时间】:2019-10-29 05:19:35
【问题描述】:

目前我在 SQL Server 上有一个函数,它进行基本检查并返回 1 (SQL Server Data Type of 'bit') 如果为 true 和 0 (SQL 'bit'的服务器数据类型) 如果为假

这是我目前拥有的:

Public Shared Function GetIsBespoke(ByVal ProductId As Integer)
        Dim Res As Boolean = False

        Dim obj_SqlConnection As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("DefaultConnectionString").ConnectionString)

        Dim obj_SqlCommand As New SqlCommand("[TBL].[fncIsBespoke]", obj_SqlConnection)
        obj_SqlCommand.CommandType = CommandType.StoredProcedure

        Dim ProductId_SqlParameter As New SqlParameter("@ProductId", SqlDbType.Int)
        ProductId_SqlParameter.Direction = ParameterDirection.Input
        ProductId_SqlParameter.Value = ProductId

        Dim Result_SqlParameter As New SqlParameter("@Result", SqlDbType.Bit)
        Result_SqlParameter.Direction = ParameterDirection.ReturnValue

        obj_SqlCommand.Parameters.Add(ProductId_SqlParameter)
        obj_SqlCommand.Parameters.Add(Result_SqlParameter)

        If Not IsDBNull(Result_SqlParameter.Value) Then
            Res = Result_SqlParameter.Value
        ElseIf IsDBNull(Result_SqlParameter.Value) Then
            Res = False
        End If

        Return Res

    End Function
USE [SRV]
GO
/****** Object:  UserDefinedFunction [TBL].[fncIsBespoke]    Script Date: 29/10/2019 2:46:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [TBL].[fncIsBespoke](@ProductID int)  
RETURNS bit   
AS   
-- Returns if product is from bespoke category
BEGIN  
    DECLARE @ret int;  
    SELECT @ret = SubCategory
    FROM Inventory.Products  
    WHERE ProductId = @ProductID  
     IF (@ret >= 665) AND (@ret <= 668) 
        RETURN 1;
    ELSE
        RETURN 0;

    RETURN NULL;
END; 

如果我在 SQL Server 中调用 PRINT [TBL].[fncIsBespoke](20334),它会返回 1

但是当我在 VB.NET 中调用 GetIsBespoke(20334) 时它返回 false?

【问题讨论】:

  • 您的 2 个示例使用不同的参数。这是一个错字吗?如果不是,PRINT [TBL].[fncIsBespoke](20336) 是返回 1 还是 0?
  • 另外,您的 ElseIf IsDBNull(Result_SqlParameter.Value) Then 可以只是 Else,因为您已经知道它是 NULL,因为它不符合 If 条件。
  • 我从来没有这样调用过 SQL 中的函数,但是您不需要在调用该函数的 SQL 中实际使用 RETURN 语句吗?
  • 感谢@ItsPete,如果您想回答我是如何忘记将SELECT 实际添加到命令中的,我很乐意将其标记为已接受。
  • “VB.NET 函数调用 SQL 函数,就是这样”。不,不是这样。 VB 代码根本不能调用 SQL 函数。您的 VB 代码执行一个调用 SQL 函数的命令,然后对它返回的值不做任何事情。当命令中的 SQL 代码没有 RETURN 语句时,您不能期望 ReturnValue 参数有值。这就像有两个 VB 函数,其中第一个调用第二个,并假设第一个将返回第二个的值,而没有自己的 Return 语句。

标签: sql-server vb.net webforms


【解决方案1】:

在 SqlCommand 中修改你的 SQL 以选择你的函数的结果:

Dim obj_SqlCommand As New SqlCommand("SELECT [TBL].[fncIsBespoke]", obj_SqlConnection)

Further information

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    • 2018-08-22
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    相关资源
    最近更新 更多