对sql server视图的访问查询

x6yk4ghg  于 2021-07-27  发布在  Java
关注(0)|答案(2)|浏览(260)

我正在尝试将access查询转换为sql server视图。我在access查询中有3个布尔列 MedTypeHealth , MedTypeSocial 以及 MedTypeEducation .
在access中,我使用以下公式:

MedType: IIf([MedTypeHealth],"H"," ") & IIf([MedTypeSocial],"S"," ") & IIf([MedTypeEducation],"E"," ")

如果设置了所有3个标志,则返回 'HSE' 如果只有 Health 旗子挂好了,我明白了 'H' .
我在SQLServer视图中有相同的列。
如何在SQLServer视图中获得相同的结果?我应该使用什么t-sql函数和代码?

a1o7rhls

a1o7rhls1#

SQLServer没有布尔数据类型,因此您可能会使用一个小的整数值或一个位。
那么,我建议 concat_ws() 和条件表达式:它很乐意忽略 null 值,这简化了 case 表达:

concat_ws('',
    case when MedTypeHealth    = 1 then 'H' end,
    case when MedTypeSocial    = 1 then 'S' end,
    case when MedTypeEducation = 1 then 'E' end
) as MedType
sigwle7e

sigwle7e2#

你可以用同样的方法 IIF 功能。
将双引号替换为单引号以指示sql server中的字符串
替换 &+ 在sql server中连接字符串
你需要明确地说出比较,比如 [MedTypeHealth]=1 在sql server中
sql server没有布尔值。你可以用 bit (0或1)但您不能这样做 SUM() 对它的操作。如果你需要的话 SUM() 操作,或者使用其他数字类型( tinyint , smallint 或执行显式类型转换 cast(MedTypeSocial as smallint) 以下是您可以使用的示例:

CREATE TABLE [MyTestTable1] (
      [MedTypeHealth] bit
    , [MedTypeSocial] bit
    , [MedTypeEducation] bit
)

INSERT INTO [MyTestTable1] 
VALUES 
      ( 1, 0, 1)
    , ( 0, 0, 1)
    , ( 1, 1, 1)
    , ( 1, 0, 0)
    , ( 0, 0, 0)

SELECT 
    *
    , IIf([MedTypeHealth]=1,'H',' ') + IIf([MedTypeSocial]=1,'S',' ') + IIf([MedTypeEducation]=1,'E',' ') WithSpace
    , IIf([MedTypeHealth]=1,'H','') + IIf([MedTypeSocial]=1,'S','') + IIf([MedTypeEducation]=1,'E','') WithoutSpace
FROM 
    [MyTestTable1]

---- drop when done. uncomment first
-- DROP TABLE [MyTestTable1]

相关问题