【问题标题】:How do I identify wether it is a male or female in the table row?如何识别表格行中是男性还是女性?
【发布时间】:2021-02-16 19:39:33
【问题描述】:

我有一个名为 tblsignup 的数据库和一个名为 registration 的表。 在注册表中,它有 ID、姓氏、年龄和性别的列。 我想确定第一行是男性还是女性

我的查询是否正确?对不起,我是菜鸟。

create function MorF (@stats int)
returns int
as
begin
    declare @stats = int
    set @stats = 0
        
    declare @gender nvarchar(50)
    set @gender = (select Gender from registration where id = 0x)
        
    if @gender = 'Male'
        begin
            set @stats = 1
        end
    else
        begin
            set @stats = 0
        end
        
    returns @stats
    
end
    

【问题讨论】:

  • 此问题不包含minimal reproducible example 的数据。
  • 您不需要@stats 参数,但您可能需要@id 参数来选择特定的注册。
  • “男性”和(大概)“女性”是性别仅有的两个选项吗?没有“空”值或“其他”(等)?
  • 您使用的是哪个 dbms? (该代码是特定于产品的。)
  • 您可能还需要CASE expression(SqlServer 特定链接,但其他 DBMS 具有相同或相似的链接)

标签: sql


【解决方案1】:

这看起来像 SQL Server。如果是这样,我会推荐一个 single statement scalar 函数。这看起来像:

create function MorF (@id int)
returns int
as
begin
    return (select (case when gender = 'Male' then 1 else 0 end)
            from registration r
            where r.id = @id
           );
end;

Here 是一个 dbfiddle。

主要变化之一是子查询的WHERE 子句。这假定传入的参数是感兴趣的id。为了清楚起见,我将参数重命名为@id

还请注意,您的本地参数 @stats 与传入的参数冲突。上面的代码只是通过避免内部参数来回避这个问题。

【讨论】:

    猜你喜欢
    • 2011-03-04
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2017-04-13
    相关资源
    最近更新 更多