先看一下我原来的SQL:declare @temptable table  
(  
cmdtype varchar(100)  
,cmdpar int  
,cmdstr nvarchar(max)  
)    
insert into @temptable  exec ('dbcc inputbuffer(' + @@spid + ')')    
select top 1 cmdstr from @temptable 
上面的SQL跟据SPID号返回当前运行的SQL语句
我现在想将其改成函数,以便我能在SELECT语句中使用。
修改后代码如下:create function ufn_GetSQLStr(@spid int)
returns nvarchar(max)
as 
begin declare @temptable table
(
cmdtype varchar(100)
,cmdpar int
,cmdstr nvarchar(max)
)insert into @temptable
exec ('dbcc inputbuffer(' + @@spid + ')')return
(
select top 1 cmdstr from @temptable
)
end
SQL分析无异常却不能创建,出错如下:
消息 443,级别 16,状态 14,过程 ufn_GetSQLStr,第 13 行
在函数内的 'INSERT EXEC' 中对带副作用的或依赖于时间的运算符的使用无效。
希望SQL高手指点一下,这个Function应如何改?

解决方案 »

  1.   

    原则:function函数,禁止使用查询、修改、添加操作。
      如:Select * from A 
           Insert Into .....
        Update A Set A.Name=xxxx from A Where A.ID=''
     
    要返回的话表或数值的话
    1>
    Create Function 函数名
    returns  table 
    as 
    begin
       declare @A table(字段名.....)   return @A
    end2>
    Create Function 函数名
    returns  varchar(200) 
    as 
    begin
       declare @A varchar(200) 
       Select top 1 @A=Name From A Where ID=''   return @A
    end
      

  2.   

    兄弟
    多谢你的回复
    其实我只是想利用一下DBCC语句得到我想要的数据
    但不知如何把DBCC语句返回的数据进行过滤才好问题暂没解决
      

  3.   

    --函数里面不能exec
    --可以用存储过程declare @temptable table
    (
    cmdtype varchar(100)
    ,cmdpar int
    ,cmdstr nvarchar(max)
    )create proc procname
    as
    begininsert into @temptable exec ('dbcc inputbuffer(' + @@spid + ')')
    select top 1 cmdstr from @temptable 
    end
      

  4.   

    用SP我也想过
    但因为我是想在SELECT语句中使用
    比如下面这样用:
    select ufn_GetSQLStr(spid),* from sys.sysprocesses
    where spid>=50换成SP不好用,所以我才想用Function的
      

  5.   


    你把这整个写到存储过程里,函数不能用exec去执行动态SQL。或者建立两个存储过程,调用。