关于在存储过程中动态选择数据表名

今天写一个功能,要求站点页面根据不同的城市显示当前城市的内容。这个功能主要是分析用户的Ip,根据Ip获取用户所在的城市,然后选择用户所在城市的内容。由于数据库架构是不同城市的内容分别放在不同的表中,如tb_1_Info, tb_2_Info,其中的数字就是城市对应的编号。在完成这个功能的过程中,我对数据库访问的用的是存储过程,但以前没有碰到在存储过程中动态的选择数据表名称。经过一段时间摸索,还是实现了这个功能,特记录一下:
存储过程代码如下:
 1ALTER PROCEDURE [dbo].[ap_BuyAndSaleAction]    
 2    @DataAction int,
 3    @ID int = 0,
 4    @UserID int,
 5    .
 6    @TableNum nvarchar(20)--外部函数传入的不同表的参数
 7AS
 8if @DataAction=0--操作代码:添加、更新、删除标记
 9BEGIN
10    declare @select varchar(1000)
11    select @select = 'insert into [tb_'+rtrim(@TableNum)+'_BuyAndSale]
12    (
13        [UserID],
14                .
15    ) 
16    values
17    (        
18        @UserID,
19        .
20    )'
21 EXEC(@select)
22    set 
23        @ID=scope_identity()
24end
25if @DataAction=1
26begin
27    declare @update varchar(1000)
28    select @update ='UPDATE [tb_'+rtrim(@TableNum)+'_BuyAndSale] SET
29        [UserID] = @UserID,
30        .
31    WHERE
32        
33        [ID] = @ID'
34    exec(@update)
35end
36if @DataAction=2
37begin
38    declare @delete varchar(100)
39    select @delete = 'delete from [tb_'+rtrim(@TableNum)+'_BuyAndSale] where  [ID] = @ID'
40    exec(@delete)
41end
42select @ID
posted on 2008-06-21 01:01  Xuemin_Zhang  阅读(576)  评论(0编辑  收藏  举报