Ms sql server - assigning a date to a variable

2019-09-21 02:10发布

问题:

Declare procursor CURSOR FOR 
SELECT CLAIMNO from RPT_CLAIM_MD_COMBO
DECLARE @myyear Integer
Declare @provar varchar(22)

open procursor

fetch next from procursor into @provar

WHILE(@@FETCH_STATUS = 0)
BEGIN
SET @myyear = (SELECT 
CASE
WHEN CONVERT(INTEGER,BTHDAT) = 0 THEN 0 
WHEN  datepart(DY,convert(date, BTHDAT)) > datepart(DY,'2015/07/01') THEN DATEDIFF(YEAR, convert(date, BTHDAT),'2015/07/01') - 1
ELSE DATEDIFF(YEAR,convert(date, BTHDAT),'2015/07/01') 
END
from RPT_CLAIM_MD_COMBO WHERE CLAIMNO = @provar)


SELECT  SERVICE_GROUP, SERVICE_CATEGORY,
CASE
WHEN @myyear - 2015 <= 0 AND @myyear - 2015 >= 5 THEN 'Early Child'
WHEN @myyear - 2015 <= 6 AND @myyear - 2015 >= 12 THEN 'Child'
WHEN @myyear - 2015 <= 13 AND @myyear - 2015 >= 17 THEN 'Adolescent'
WHEN @myyear - 2015 <= 18 AND @myyear - 2015 >= 21 THEN 'Transitional'
WHEN @myyear - 2015 <= 22 AND @myyear - 2015 >= 64 THEN 'Adult'
WHEN @myyear - 2015 >= 65 THEN 'Geriatric'
ELSE '0'  
END AS Age_desc,
SUM(CONVERT(MONEY, TOPAY)) AS PAID_AMT    
FROM RPT_CLAIM_MD_COMBO
WHERE SERVICE_FY = '2016' and DISTYP = 'P' AND CLAIMNO = @provar 
GROUP BY 
SERVICE_GROUP,SERVICE_CATEGORY,
CASE
WHEN @myyear - 2015 <= 0 AND @myyear - 2015 >= 5 THEN 'Early Child'
WHEN @myyear - 2015 <= 6 AND @myyear - 2015 >= 12 THEN 'Child'
WHEN @myyear - 2015 <= 13 AND @myyear - 2015 >= 17 THEN 'Adolescent'
WHEN @myyear - 2015 <= 18 AND @myyear - 2015 >= 21 THEN 'Transitional'
WHEN @myyear - 2015 <= 22 AND @myyear - 2015 >= 64 THEN 'Adult'
WHEN @myyear - 2015 >= 65 THEN 'Geriatric'
ELSE '0'  
END 

fetch next from procursor into @provar 

END

CLOSE procursor 

What I am trying to do is get all the users from RPT_CLAIM_MD_COMBO table. 1st check for their age. If the DY of birthdate of the user > DY of 2015/07/01 then reduce the his age by 1 else keep the same age.

Once the age is calculated I have to display the expenditure according to age(i,e group by age). I've coded so much and I am getting this error Msg 329, Level 16, State 1, Line 21 Each GROUP BY expression must contain at least one column reference

回答1:

You can't assign a variable like that. Besides, what's the point? Where are you using that variable at? Just remove the set @MYYEAR = and you should be fine. If you really want to assign that variable with that logic, do it outside of your main SELECT statement.

declare @MYYEAR int
set @MYYEAR = 
(SELECT  
    CASE
        WHEN CONVERT(INTEGER,BTHDAT) = 0 THEN 0
        WHEN  datepart(DY,convert(date, BTHDAT)) > datepart(DY,'2015/07/01') THEN DATEDIFF(YEAR, convert(date, BTHDAT),'2015/07/01') - 1
        ELSE DATEDIFF(YEAR,convert(date, BTHDAT),'2015/07/01')  
    END
FROM SomeTable)

SELECT  
    SERVICE_GROUP, 
    SERVICE_CATEGORY,
    @MYYEAR
FROM
    SomeOtherTable