我不知道在T-SQL中是否可以执行此操作,但我想迭代每个月并使用月份编号作为行名称的一部分。当尝试使用我的月份数变量时,我无法连接行的名称。这是我的代码示例。非常感谢您提供任何帮助。
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
答案 0 :(得分:2)
你是在初始化@mes = 0吗?为此,您可能必须将update语句构建为文本字符串,然后执行它。
Set @sql = 'update #Reporte set m' + @xmes + ' = ''' + @meta + ''' where ven = ''' + @ven + ''''
Exec(@sql)
答案 1 :(得分:0)
你想要月份名字吗?在这里,您有2个可行的解决方案,以获取月份名称:
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
问候!