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