SQL查询动态列的方法

来源:百度知道 编辑:UC知道 时间:2024/06/24 17:25:17
有一个表,列名为包括name varchar(10),month_t varchar(7),D1 int,D2 int,D3 int,D4 int,D5 int,D6 int,D7 int ......D31 int 共33列。
现在给一个变量@day int,
当这个变量为1时,执行查询 select * from 表 where D1=1
当这个变量为2时,执行查询 select * from 表 where D2=2
当这个变量为3时,执行查询 select * from 表 where D3=3
......
当这个变量为31时,执行查询 select * from 表 where D31=31

请问这个存储过程怎么写??
fangliang911的猜想完全正确。

create PROCEDURE XXX(@day int) as
begin
declare @v_sql VARCHAR(512)
declare @cDay varchar(2)
set @cDay=cast(@day as varchar(2))
set @v_sql='select * from 表 where D'+@cDay+'='+@cDay
Execute v_sql
END

首先,这张表本身就很不合理,如果不是硬要用这种结构,推荐您使用一列存储数据,我有点明白您可能是要最后通过select生成一张月报表,不知我的猜想对吗?(好像还是没搞清楚)

就事论事吧
create proc xxx @day int
as
if @day=1 select * from 表 where D1=@day
if @day=2 select * from 表 where D2=@day
if @day=3 select * from 表 where D3=@day
if @day=4 select * from 表 where D4=@day
后面就不写了,共要31行,恐怕也是最好想出的办法了

你这貌似 只能一个一个判断:
create procedure pro_info
@day int
as
if @day=1
begin
select * from 表 where d1=1
end
if.....

晕,有这样建库的?

create proc xxx @day int
as
declare @D int
set @D=@D+@day
select * from 表 where @D=@day

Oracle 数据库:

create or replace PROCEDURE XXX(
day INTEGER;
)IS