2014-09-29 236 views
0

我有一個表格,包括1列ID和12個月的月份(Month01到Month12)。如果我有一個參數@月= 9,我怎麼可以比較獲得列Month01到Month09沒有Month10,Month11,Month12。請幫幫我!我該如何解決這個問題?

回答

0

,你也可以嘗試了這一點:)

DECLARE @month int = 9 
DECLARE @Sql nvarchar(100) ='' 
DECLARE @pos int = 1 
WHILE(@pos <= @month) 
BEGIN 
    SET @Sql = @Sql + (',month' + right('00'+ rtrim(@pos), 2)) 
    SET @pos = @pos + 1 
END 
SET @Sql= 'SELECT ID ' [email protected] + ' FROM table' 
EXEC sp_executesql @Sql 
0
DECLARE @month int 
DECLARE @tableName nvarchar(128) 

SET @month = 9; 
SET @tableName = 'months' -- YOUR TABLE's NAME 

DECLARE @query nvarchar(2048) 
SET @query = 
'SELECT id, ' + STUFF((SELECT DISTINCT ', ' + name 
    FROM sys.columns WHERE name LIKE'Month%' 
    AND object_id = OBJECT_ID(@tableName) 
    AND CONVERT(INT, RIGHT(name, 2)) <= @month 
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') 
    + ' FROM ' + @tableName; 

EXEC(@query) 
+0

你不應該過濾的''object_id' sys.columns'?如果另一個表有一個名爲'MonthValue'的列呢? – 2014-10-07 07:14:32

+0

@AndriyM,你說得對。 Fix'd。 – 2014-10-07 15:51:40

0

廝磨的回答是更優雅,但下面是一個另類的「基本」的方式來做到這一點:

DECLARE @month INT 
SET @month = 9 

IF @Month = 1 
BEGIN 
    SELECT Id, Month01 
    FROM MonthlyData 
END 

IF @Month = 2 
BEGIN 
    SELECT Id, Month01, Month02 
    FROM MonthlyData 
END 

-- Repeat for months 3-9 

IF @Month = 9 
BEGIN 
    SELECT Id, Month01, Month02, Month03, Month04, 
     Month05, Month06, Month07, Month08, Month09 
    FROM MonthlyData 
END 

-- Repeat for months 10-12 

見我SQL Fiddle

0
declare @str varchar(1000) 

SELECT @str= coalesce(@str + ', ', '') + a.name 
FROM (
     Select name from sys.columns 
     where object_id = OBJECT_ID('table_months') 
     and isnumeric(right(name,2))= 1 and name like 'month%' 
     and cast(right(name,2) as int) < '03') a 

- 而不是 '03' 的你使用一個變量並分配所需的飛蛾數量

declare @sql nvarchar(100) 

set @sql = 'select ID, '+ @str+' from table_months' 

exec sp_executesql @sql