怎么写一个sql语句,可以检查一个字段的值,如果是true返回1,是false返回0?多谢!

charlesxu 2011-07-25 02:15:35
要求返回0或者1的时候就像返回这个字段的值一样。
...全文
1848 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
liang145 2011-07-25
  • 打赏
  • 举报
回复

create table Table01
(字段01 bit,字段02 bit,字段03 bit)
insert Table01
select 'true', 'false', 'true' union all
select 'false', 'false', 'true'

declare @sql nvarchar(4000)
set @sql=''
select @sql=@sql+' union all select Rowid,'''+[name]+''' as ColnumName,'
+'case when '+[name]+'=''true'' then 1 else 0 end as [value] from T' from sys.columns
where [object_id]= object_id('Table01')
set @sql=';with T as (select Row_number()over(order by getdate()) as Rowid,* from Table01)'+
stuff(@sql,1,10,'')
exec(@sql)

--Rowid ColnumName value
---------------------- ---------- -----------
--1 字段01 1
--2 字段01 0
--1 字段02 0
--2 字段02 0
--1 字段03 1
--2 字段03 1
--
--(6 row(s) affected)
attababy 2011-07-25
  • 打赏
  • 举报
回复
select
case value
when 1 then 'true'
when 0 then 'false'
else 'unknown'
end
from ...
charlesxu 2011-07-25
  • 打赏
  • 举报
回复
比如:Table01

字段01,字段02,字段03
true, false, true

怎么返回以下的报表:
字段01 1
字段02 0
字段03 1
liang145 2011-07-25
  • 打赏
  • 举报
回复

create table #tb(bool bit)
insert #tb
select 'true' union all
select 'false' union all
select 'false' union all
select 'true'

select case bool when 'true' then 1 else 0 end as bool from #tb
-晴天 2011-07-25
  • 打赏
  • 举报
回复
不明白楼主的意思,在MSSQL里,逻辑型数据是由bit类型来处理的,true 就是1,false 就是0.
create table tb(col bit)
insert into tb select 1 union all select 0
go
select * from tb
/*
col
-----
1
0

(2 行受影响)

*/
go
drop table tb
闹铃 2011-07-25
  • 打赏
  • 举报
回复

select case value
when 'true' then 1
when 'false' then 0 end
cd731107 2011-07-25
  • 打赏
  • 举报
回复
select case when 字段='true' then 1 else 0 end as [新字段名]
百年树人 2011-07-25
  • 打赏
  • 举报
回复
select case when 字段='true' the 1 else 0 end from tb

34,594

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧