读书人

送分请问一个比较简单的语句

发布时间: 2012-08-25 10:06:20 作者: rapoo

送分请教一个比较简单的语句
我从b表select出来一些字段数据,要插入到a表中。
插入前要判断b表其中一个字段,完后决定往a表插正值还是负值

比如b表为
order num status_flag
r001 5 1
r002 6 0
r003 7 0
r004 8 1

如果status_flag为1就往a表里插正的num,如果为0就往a表里插负的num
a表就应该为
order num status_flag
r001 5 1
r002 -6 0
r003 -7 0
r004 8 1


这个语句怎么写?
inert into a(order,num,status_flag)
select order,num,status_flag from b
if b.status_flag =1
then
num=num
else
if
b.status_flag =0
then
num=-num
endif
endif

是这样写吗?

[解决办法]

SQL code
--> 测试数据:[test]if object_id('[test]') is not null drop table [test]create table [test]([order] varchar(4),[num] int,[status_flag] int)insert [test]select 'r001',5,1 union allselect 'r002',6,0 union allselect 'r003',7,0 union allselect 'r004',8,1if object_id('[a]') is not null drop table acreate table a([order] varchar(4),[num] int,[status_flag] int)goinsert a select [order],case when [status_flag]=0 then -[num] else [num] end,[status_flag]from testgoselect * from a/*order    num    status_flag-----------------------------------r001    5    1r002    -6    0r003    -7    0r004    8    1*/
[解决办法]
插入的时候用case判断一下就行了

读书人网 >SQL Server

热点推荐