【发布时间】: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