简体   繁体   中英

Iterate through months using T-SQL

I don't know if this operation is possible in T-SQL, but I want to iterate through each month and use the month number as part of the name of a row. When a try to use my variable of the month number I can't concatenate the name of the row. Here is an example of my code. Thanks a lot in advance for any help.

WHILE @mes < 12 BEGIN
SET @mes = @mes + 1
SET @xmes = iif(@mes>9,'0'+convert(varchar, @mes),convert(varchar, @mes))


    DECLARE #Meta CURSOR LOCAL FOR
        SELECT ven, meta FROM vendmeta
    OPEN #Meta
    FETCH NEXT FROM #Meta INTO @ven, @meta

    WHILE @@FETCH_STATUS = 0
    BEGIN   
        --here is where I need to use my variable but not work 
        update #Reporte set m+@xmes = @meta where ven = @ven

    FETCH NEXT FROM #Meta INTO @ven, @meta
    END 
    CLOSE #Meta
    DEALLOCATE #Meta

END

Are you initializing @mes = 0? To do this, you might have to build the update statement as a text string and then execute it.

Set @sql = 'update #Reporte set m' + @xmes + ' = ''' + @meta + ''' where ven = ''' + @ven + ''''
Exec(@sql)

Do you want the month names ? Here you have 2 posible solutions in order to get the month names:

1.-

    ; WITH cte AS (
    SELECT CAST( '19000101' AS DATE ) AS dtColumn
    UNION ALL
    SELECT DATEADD( M , 1 , dtColumn ) 
    FROM cte 
    WHERE DATEADD( M , 1 , dtColumn ) < '19010101' 
)

SELECT dtColumn, UPPER( DATENAME( M, dtColumn ) ) AS monthName 
 FROM cte

2.-

; WITH cteLVL1 AS( 
    SELECT 1 AS colName UNION ALL SELECT 1 
)
, cteLVL2 AS(
    SELECT 1 AS colName FROM cteLVL1 AS a CROSS JOIN cteLVL1 AS b
)
, cteLVL3 AS(
    SELECT 1 AS colName FROM cteLVL2 AS a CROSS JOIN cteLVL2 AS b
)
, cte AS(
    SELECT 1 AS colName , ROW_NUMBER() OVER ( ORDER BY colName ) AS rn , CAST( '19991201' AS DATE ) AS dtColumn FROM cteLVL3 AS a
)

SELECT TOP 12 colName
, rn
, dtColumn
, DATEADD( M , rn , dtColumn ) AS dtColumnCalculated
, DATENAME( M , DATEADD( M , rn , dtColumn ) ) AS monthNameCol
FROM cte

Regards!

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