我该如何解决这个问题?

时间:2014-09-29 08:29:06

标签: tsql

我有一个表包括1列ID和12列月(Month01到Month12)。如果我有一个参数@ month = 9,我如何比较获得没有Month10,Month11,Month12的第Month01到Month09列。请帮帮我!

4 个答案:

答案 0 :(得分: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 ' +@Sql + ' FROM table'
EXEC sp_executesql @Sql

答案 1 :(得分: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)

答案 2 :(得分:0)

Simo的答案更优雅,但下面是另一种选择&#34; basic&#34;这样做的方法:

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

答案 3 :(得分: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

- 而不是&#39; 03&#39;您使用变量并指定所需的飞蛾数

declare @sql  nvarchar(100)

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

exec sp_executesql @sql