2012-04-10 2 views
3

아래의 SQL이 NULL을 반환하는 경우 어떻게 1을 반환 할 수 있습니까? (의사 코드) 같은SQL 서버에서 int가 1 씩 증가합니까?

뭔가 :

if sql return NULL value 
then set value to one 
otherwise returning sql result value. 

는 SQL 결과가 NULL 인 경우 1로 디폴트 값을 정의하기위한 어떤 SQL이 있습니까?

SELECT Max(iCategoryOrder)+1 
FROM [IVRFlowManager].[dbo].[tblCategory] 
WHERE iCategoryLevel = 1 

답변

4

사용 ISNULL 연산자와 같은 :

ISNULL(your_field, 1) 

시도가 다음

Select ISNULL(Max(iCategoryOrder), 0) + 1 
from [IVRFlowManager].[dbo].[tblCategory] 
where iCategoryLevel = 1 
+0

고마워요. 정확히 내가 원하는 것입니다. –

5

옵션 1

사용 ISNULL()

설명

NULL을 지정된 대체 값으로 바꿉니다.

SELECT MAX(ISNULL(iCategoryOrder, 0))+1 
FROM  [IVRFlowManager].[dbo].[tblCategory] 
WHERE  iCategoryLevel = 1 

옵션 2

사용 COALESCE()

SELECT MAX(COALESCE(iCategoryOrder, 0))+1 
FROM  [IVRFlowManager].[dbo].[tblCategory] 
WHERE  iCategoryLevel = 1 

설명

처음 널 (null)이 아닌 expressio를 돌려줍니다 그 논쟁 중에 n.

+0

COALESCE()는 표준 SQL이기 때문에 제 의견으로는 더 좋습니다. – fancyPants

관련 문제