日期:2014-05-17  浏览次数:20521 次

怎样读取到列的名字?
在提问之前先感谢一个人,就不说名字了,显得太阿谀奉承了,知道您一定看到的!希望能坚持!
回到问题上
--------------表结构\语句-------
SQL code
IF OBJECT_ID('test99')iS NOT NULL DROP TABLE test99
 go
  create table test99
  (id int ,
  "Jan-2012" money,
  "Feb-2012" money,
  "Mar-2012" money,
  "Apr-2012" money,
  "May-2012" money)
  select * from test99
  
  insert into test99
  select 001,12345,978,4121,49789,979
  union all
  select 002,12345,978,4121,49789,979
    union all
   select 003,12345,978,4121,49789,979
     union all
   select 001,12345,978,4121,49789,979
     union all
   select 002,12345,978,4121,49789,979
     union all
   select 003,12345,978,4121,49789,979


想写这样的存储
SQL code
 create proc customer1
(@Id int
  ,@beginyear int
  ,@beginmonth int
  ,@endyear int
  ,@endmonth int)
  as
  select ? from test99
  where ID=@Id and .........


SQL code
exec customer1 1,2012,2,2012,4

输出

不知道怎样提取字段名字与参数比较
这样的存储怎么写,还是有更好的方法

------解决方案--------------------
SQL code

--怎么可能   当你执行
exec customer 1,2012,2,2012,4
--会出现ID>1的结果

------解决方案--------------------
SQL code
CREATE proc customer1
(@Id varchar(10)
  ,@beginyear varchar(10)
  ,@beginmonth int
  ,@endyear varchar(10)
  ,@endmonth int)
  as
declare @sql varchar(max),@execsql  varchar(max) 
set @sql = 'id'
;with mon as
(select 'Jan' En, 1 Num union
 select 'Feb', 2 union
 select 'Mar', 3 union
 select 'Apr', 4 union
 select 'May', 5 union
 select 'Jun', 6 union
 select 'Jul', 7 union
 select 'Aug', 8 union
 select 'Sep', 9 union
 select 'Oct', 10 union
 select 'Nov', 11 union
 select 'Dec', 12 
 )
select @sql = isnull(@sql,'') + ',['+ a.name + ']'
from sys.syscolumns a, mon b 
where a.id = object_id('test99') and left(a.name,3) = b.En and b.Num between @beginmonth and @endmonth 
and right(a.name,4) between @beginyear and @endyear
set @execsql =  '
  select '+@sql+' from test99
  where ID = '+@Id
--print @execsql
exec(@execsql)

GO

 exec customer1 1,2012,2,2012,4
/*id          Feb-2012              Mar-2012              Apr-2012
----------- --------------------- --------------------- ---------------------
1           978.00                4121.00               49789.00
1           978.00                4121.00               49789.00

(2 行受影响)
*/

------解决方案--------------------
刚洗完澡,既然磊仔搞好了我就不写了,不过磊仔我到建议你left那里改成:
SUBSTRING(NAME,0, CHARINDEX('-',name ,0))='jan' THEN '1' 
 WHEN SUBSTRING(NAME,0, CHARINDEX('-',name ,0))='feb' THEN '2' 
 WHEN SUBSTRING(NAME,0, CHARINDEX('-',name ,0))='mar' THEN '3' 
 WHEN SUBSTRING(NAME,0, CHARINDEX('-',name ,0))='apr' THEN '4' 
 WHEN SUBSTRING(NAME,0, CHARINDEX('-',name ,0))='may' THEN '5' 这样稳当一点你也不能保证他的数据一定是3位
------解决方案--------------------
探讨

SQL code
CREATE proc customer1
(@Id varchar(10)
,@beginyear varchar(10)
,@beginmonth int
,@endyear varchar(10)
,@endmonth int)
as
declare @sql varchar(max),@execsql varchar(max)
set @sql……