学院首页>网络编程>SQL Server>如何在存储过程中使用变量代替表名

如何在存储过程中使用变量代替表名

作者:Tanxufeng 来源:统一教学网 添加时间:2006-5-21 10:57:19

Q atrie560lcd:
我想在存储过程中使用变量代替表名,以便对相同格式的不同的表进行数据更改,但我不知道该怎么做。
  create procedure proc1
  as
  declare @tbname varchar(11),@cs int
  update @tbname set zd1=zd1+@cs
结果显示:第4行有错误,必须声明变量 @tbname
  请问应该怎样写?

A回答:

将 Update @tbname set zd1=zd1+@cs
该为:
  update Table1 @tbname set zd1=zd1+@cs
或 Update Table1 as @tbname set zd1=zd1+@cs (注:table1 为原表名)
 
peiyan的意见:
CREATE PROCEDURE
Find_Dj @table_name varchar(20),@strsql varchar(20)
 
AS
 
declare @sql varchar(200)
 
set @sql=''select * from ''+@table_name+ '' where ''+ @strsql
execute(@sql)
 
乐全云的意见:
create procedure proc1
  as
  declare @tbname varchar(11),@cs int
declare @SQLSTRING NVARCHAR(4000)
SET @SQLSTRING=N'' update ''+@tbname+'' set zd1=zd1+''+@cs
EXEC sp_executesql @SQLSTRING

站内搜索