简体   繁体   English

SQL Server:将“ y”解释为BIT值

[英]SQL Server: interpreting 'y' as BIT value

In C, when you compared true/false value to 1/0, it worked very well. 在C语言中,将true / false值与1/0进行比较时,效果很好。

I would want the similar possibility with SQL Server - when I have a bit column, I would like to compare myBitField = 'y' / myBitField = 'n' 我想要与SQL Server类似的可能性-当我有一个bit ,我想比较myBitField = 'y' / myBitField = 'n'

Is there anything I can do about that? 有什么我可以做的吗? Maybe change some SQL interpreter settings or something? 也许更改一些SQL解释器设置或其他内容?

Example of what I would like to do: 我想做的事的例子

select * from
(
   select CAST(1 AS BIT) as result
) as main
where main.result = 'y'

Currently, it throws an error, and I would like it to return 1/true/'y', whatever, but I would like it to be able to make that comparison. 当前,它引发一个错误,并且我希望它返回1 / true /'y',但无论如何,但是我希望它能够进行比较。

I suppose you want to do it for some yes/no thing. 我想你想做是/不是的事情。 But this is generally a wrong concept, your application which is accessing the SQL Server should interpret y as a 1 and n as a 0 and afterwards set the correct parameters for the query. 但这通常是一个错误的概念,正在访问SQL Server的应用程序应将y解释为1,将n解释为0,然后为查询设置正确的参数。 You should not (actually I'm temped to write "must not") do this in SQL Server, that's what you have a business logic for. 您不应该(实际上我很想写“绝对不能”)在SQL Server中执行此操作,这就是您要使用的业务逻辑。

As others have said, BIT and CHAR / VARCHAR are entirely different datatypes. 就像其他人所说的,BIT和CHAR / VARCHAR是完全不同的数据类型。 But if you want to cast them during the select, you can use CASE expression like so: 但是,如果要在选择期间强制转换它们,则可以使用CASE表达式,如下所示:

-- Reading string as BIT
SELECT CAST(CASE RESULT WHEN 'Y' THEN 1 WHEN 'N' THEN 0 ELSE NULL END AS BIT) RESULT

-- Reading BIT as string
SELECT CAST(CASE RESULT WHEN 1 THEN 'Y' WHEN 0 THEN 'N' ELSE NULL END AS CHAR(1)) RESULT

And that's about as far as your options go here, far as I can understand. 据我所知,这就是您的选择。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM