日期:2014-05-18  浏览次数:20425 次

怎样在动态SQL中加入有效变量?
DECLARE   @tableName   AS   NVARCHAR(155)
DECLARE   @sql   AS   NVARCHAR(255)
DECLARE   @rows   as   int

DECLARE   table_cursor   CURSOR   FOR   SELECT   [name]   FROM   sysobjects   WHERE   (xtype   =   'u ')
OPEN   table_cursor

FETCH   NEXT   FROM   table_cursor   INTO   @tableName

WHILE   @@FETCH_STATUS   =   0
BEGIN
SET   @sql= 'SELECT   @rows=count(*)   from   '+@tableName
EXEC(@sql)
print   @rows
FETCH   NEXT   FROM   table_cursor   INTO   @tableName
END
CLOSE   table_cursor

这段SQL执行报如下错误:
服务器:   消息   137,级别   15,状态   1,行   1
必须声明变量   '@rows '。

请问怎样写才能不报这样的错?[print   @rows这句必须要,我是要根据每个表的记录数做相应的处理,这里只暂时将其打印出来]
或者有没有更好的解决方案?

------解决方案--------------------
DECLARE @tableName AS NVARCHAR(155)
DECLARE @sql AS NVARCHAR(255)
DECLARE @rows as int

DECLARE table_cursor CURSOR FOR SELECT [name] FROM sysobjects WHERE (xtype = 'u ')
OPEN table_cursor

FETCH NEXT FROM table_cursor INTO @tableName

WHILE @@FETCH_STATUS = 0
BEGIN

SET @sql=N 'SELECT @rows=count(*) from '+@tableName
EXEC SP_EXECUTESQL @sql,N '@rows int out ',@rows out
print @rows

FETCH NEXT FROM table_cursor INTO @tableName
END
CLOSE table_cursor
DEALLOCATE table_cursor
------解决方案--------------------

动态sql语句基本语法
1 :普通SQL语句可以用Exec执行

eg: Select * from tableName
Exec( 'select * from tableName ')
Exec sp_executesql N 'select * from tableName ' -- 请注意字符串前一定要加N

2:字段名,表名,数据库名之类作为变量时,必须用动态SQL

eg:
declare @fname varchar(20)
set @fname = 'FiledName '
Select @fname from tableName -- 错误,不会提示错误,但结果为固定值FiledName,并非所要。
Exec( 'select ' + @fname + ' from tableName ') -- 请注意 加号前后的 单引号的边上加空格

当然将字符串改成变量的形式也可
declare @fname varchar(20)
set @fname = 'FiledName ' --设置字段名

declare @s varchar(1000)
set @s = 'select ' + @fname + ' from tableName '
Exec(@s) -- 成功
exec sp_executesql @s -- 此句会报错


declare @s Nvarchar(1000) -- 注意此处改为nvarchar(1000)
set @s = 'select ' + @fname + ' from tableName '
Exec(@s) -- 成功
exec sp_executesql @s -- 此句正确

3. 输出参数
declare @num int, @sql nvarchar(4000)
set @sql= 'select count(*) from tableName '
exec(@sql)


--如何将exec执行结果放入变量中?

declare @num int, @sql nvarchar(4000)
set @sql= 'select @a=count(*) from tableName '
exec sp_executesql @sql,N '@a int output ',@num output
select @num