天天看点

在sql语句中,怎样将参数做为表名传递到查询语句中

今天为了提取出公共的fuction提高执行效率,需要传递表的字段作为参数,语法可以通过,但是查询结果不正确。

将表字段参数换成实际的字段就可以,问题出在“如果将表名,字段名做为参数传递到Sql Server中”

 create   function   backtoCount(@tablename   varchar(50))  

 returns   int

 as

 begin

 declare   @count   int

 select   @count=count(*)   from   @tablename

 return   @count

 end

 但是这样的时候会报错,说变量@tablename要声明

 对于表名作为变量,我们可以使用object_name(id)方法

 create   function   backtoCount(@tablename   varchar(50))  

 returns   int

 as

 begin

 declare   @count   int

 select   @count=rows   from   sysindexes   where   indid   in   (0,1)   and   object_name(id)[email protected]

 return   @count

 end

 GO

 --查sysobjects表有多少行

 select   dbo.backtoCount( 'sysobjects ')

 对于字段变量的话,必须执行动态语句,但是函数里边不能用exec,建议使用存储过程实现。

 解决方法:动态SQL

 create   procedure   f_count(@tablename   varchar(50))

 as

 declare   @str   as   varchar(1000)

 set   @str= 'select   count(*)   as   a   from   '[email protected]

 print   @str

 exec   (@str)

 exec   f_count   'sysfiles '