简体   繁体   中英

how should i validate if one datetime field is greater then second datetime in sql server 2008 using IF else statement?

I'm writing a sql query in which i want to check if one datetime field from table a is greater then a datetime field in table b.

Any help would be appriciated.

My query looks something like this:

SELECT A.AFIELD, B.BFIELD, ( <HERE I WANT TO PUT THE VALIDATION STATEMENT> ) AS 'VALIDATED AS' FROM A JOIN B ON A.AFIELD=B.AFIELD

Validation statement should be like

If (A.XFIELD < B.YFIELD)
THEN "YES"
ELSE
"NO"

I'm trying it but not able to do so, it will be greatful if, anybody can help.

你要案情陈述

CASE WHEN datediff(d,A.XFIELD, B.YFIELD) > 0 THEN 'YES'  ELSE  'NO' END

Something like this

SELECT 
A.AFIELD, 
B.BFIELD, 
(
CASE WHEN A.XFIELD < B.YFIELD THEN 'YES'  
ELSE  'NO' 
END
) AS 'VALIDATED AS' 

FROM A JOIN B ON A.AFIELD=B.AFIELD

you could use case statement for this.

Syntax:

Simple CASE expression:

CASE input_expression 
     WHEN when_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END 

Searched CASE expression:

CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

In your case it would be like:

SELECT 
A.AFIELD, 
B.BFIELD, 
(
CASE 
WHEN
 A.XFIELD < B.YFIELD THEN 'YES'  
ELSE  'NO' 
END
) AS 'VALIDATED AS' 
FROM A JOIN B ON A.AFIELD=B.AFIELD

For details on Case refer here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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