【问题标题】:How to generate possible binary combinations of 3 bits binary?如何生成 3 位二进制的可能二进制组合?
【发布时间】:2020-05-24 21:27:50
【问题描述】:

我写了下面的函数。更多细节请参考函数中的 cmets。

 DROP FUNCTION dbo.[combination]
 GO
CREATE FUNCTION [dbo].[combination] (
    @Fruits VARCHAR(200),  --comma separated value
    @Vegetables VARCHAR(200),
    @Junkfood NVARCHAR(max)
) RETURNS @FinalTable table (
    result int

)
AS BEGIN
    DECLARE @countisFruit int    DECLARE @countisVegetable int     DECLARE @countisJunkfood int DECLARE @test int
    DECLARE @isFruitAvailable int DECLARE @isVegetableAvailable int DECLARE @isJunkFoodAvailable int
    SELECT @isFruitAvailable = LEN(REPLACE(@Fruits, CHAR(44), ''))
    SELECT @isVegetableAvailable = LEN(REPLACE(@Vegetables, CHAR(44), ''))
    SELECT @isJunkFoodAvailable = LEN(REPLACE(@Junkfood, CHAR(44), ''))


    BEGIN

    IF @countisFruit > 0
        BEGIN 
        SELECT @isFruitAvailable = 1
        END
    IF @countisVegetable > 0
        BEGIN 
        SELECT @isVegetableAvailable = 1
        END
    IF @countisJunkfood > 0
        BEGIN 
        SELECT @isJunkFoodAvailable = 1
        END


    --<.......Here I want to have if conditions based on what kinds of food is available 
    -- i can achieve it  by having if conditions like 
    --if (@countisFruit > 0 AND @countisVegetable >0 AND @countisJunkfood> 0 )
    --if (@countisFruit = 0 AND @countisVegetable >0 AND @countisJunkfood> 0 ) and so on possible conditions 
    -- I am thinking reading from @count<X> in every if statement might slow down my function 
    --- so I can represent possible combinations in binary  like 000, 101, 111 ... for that I will have to do some logic on @countisFruit and rest @count<X> variables.
    -- Please suggest how can i achieve that

RETURN
END
GO

请建议我如何在 sql 函数中实现这些组合或类似的东西。我正在尝试优化此功能中涉及的许多 if。

【问题讨论】:

  • 很难猜出这段代码的实际目的是什么。请提供示例数据、预期结果以及您想要达到的目标的说明。
  • :(...尝试用更多信息编辑它
  • @vidyashi 。 . .作为提示:样本数据和期望的结果真的很有帮助。如果你真的需要一个函数,输入和输出的例子,以及清晰的解释帮助。
  • 这是什么数据库?
  • 是sql数据库

标签: sql function binary


【解决方案1】:

注意解释和参数没有任何关系。 如果要查找逗​​号分隔列表中的元素数: 假设这是针对 SQL Server 的,这里有一种查找计数的方法。

declare @input1 varchar(555) ='23,ABC,67, PQR5,267,XYZ236,Emp1, Emp2', @countInput1 int

SELECT @countInput1 = SUM(LEN(@input1) - LEN(replace(@input1, ',', '')) +1)  
SELECT @countInput1 as countInput1

因此您也可以对其他 2 个执行相同操作,您可以找到插入的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-23
    • 2020-07-13
    相关资源
    最近更新 更多