日期:2014-05-18 浏览次数:20572 次
CREATE PROC TEST ( @Table varchar(20), @name int ) as SELECT MAX(ID) FROM @TABLE WHERE IDname=@name
------解决方案--------------------
CREATE PROC TEST ( @Table varchar(20), @colname varchar(20) ) as exec('SELECT MAX('+@colname+') FROM '+@TABLE)
------解决方案--------------------
SELECT MAX(@colname) FROM @TABLE
这么些不行,因为@TABLE定义为字符串变量了,并非表格名称。
2楼的才是正确的。
------解决方案--------------------
try this,
CREATE PROC TEST ( @Table varchar(20), @colname varchar(20), @outmax int output) as begin declare @sql varchar(6000) select @sql='SELECT MAX('+@colname+') FROM '+@TABLE create table #o(outmax int) insert into #o(outmax) exec(@sql) select @outmax=outmax from #o end -- 调用方法 declare @om int exec TEST [表名],[字段名],@om output select @om
------解决方案--------------------
CREATE PROC TEST ( @Table varchar(20), @colname varchar(20), @outmax int output ) as declare @sql nvarchar(100) set @sql='SELECT @max=MAX('+@colname+') FROM '+@TABLE exec sp_executesql @sql,N'@max int output',@outmax output
------解决方案--------------------
--调用: declare @max int exec TEST '表名','字段名',@max output select @max
------解决方案--------------------
方法2,
create proc TEST ( @Table varchar(20), @colname varchar(20), @outmax int output) as begin declare @sql nvarchar(4000) select @sql=N'SELECT @m=MAX('+@colname+') FROM '+@TABLE exec sp_executesql @sql,N'@m int output',@m=@outmax output end -- 调用方法 declare @om int exec TEST [表名],[字段名],@om output select @om
------解决方案--------------------