TSQL如何在用户定义函数中输出PRINT?

基本上我想在用户定义的函数中使用PRINT语句来辅助我的debugging。

不过,我收到以下错误;

函数中“PRINT”中副作用或时间相关运算符的使用无效。

可以这样做吗?

无论如何,以帮助我的用户定义函数debugging?

不,对不起。 SQL Server中用户定义的函数实际上是有限的,因为它们是确定性的。 就我所知,没办法。

您是否尝试过使用Visual StudiodebuggingSQL代码?

提示:生成错误。

 declare @Day int, @Config_Node varchar(50) set @Config_Node = 'value to trace' set @Day = @Config_Node 

你会得到这个消息:

将varchar值“跟踪”转换为数据typesint时转换失败。

我通过暂时重写我的函数来解决这个问题:

 IF OBJECT_ID ('[dbo].[fx_dosomething]', 'TF') IS NOT NULL drop function [dbo].[fx_dosomething]; GO create FUNCTION dbo.fx_dosomething ( @x numeric ) returns @t table (debug varchar(100), x2 numeric) as begin declare @debug varchar(100) set @debug = 'printme'; declare @x2 numeric set @x2 = 0.123456; insert into @t values (@debug, @x2) return end go select * from fx_dosomething(0.1) 

过去我一直倾向于分两个阶段来开展工作。 第一阶段将把它们视为相当正常的SQL查询,并确保我得到正确的结果。 在我确信它正在按照需要执行之后,我会将其转换为UDF。

使用扩展过程xp_cmdshell来运行一个shell命令。 我用它来打印输出到一个文件:

 exec xp_cmdshell 'echo "mytextoutput" >> c:\debuginfo.txt' 

这将创build文件debuginfo.txt,如果它不存在。 然后将文本“mytextoutput”(不带引号)添加到文件中。 任何对函数的调用都会写入一行。

您可能需要首先启用这个db-server属性(默认=禁用),我认为这可能不是喜欢dba的生产环境。

你不能。

你可以从stored procedure调用一个function并debugging一个stored procedure (这将进入function

你可以尝试返回你想要检查的variables。 例如,我有这个function:

 --Contencates seperate date and time strings and converts to a datetime. Date should be in format 25.03.2012. Time as 9:18:25. ALTER FUNCTION [dbo].[ufn_GetDateTime] (@date nvarchar(11), @time nvarchar(11)) RETURNS datetime AS BEGIN --select dbo.ufn_GetDateTime('25.03.2012.', '9:18:25') declare @datetime datetime declare @day_part nvarchar(3) declare @month_part nvarchar(3) declare @year_part nvarchar(5) declare @point_ix int set @point_ix = charindex('.', @date) set @day_part = substring(@date, 0, @point_ix) set @date = substring(@date, @point_ix, len(@date) - @point_ix) set @point_ix = charindex('.', @date) set @month_part = substring(@date, 0, @point_ix) set @date = substring(@date, @point_ix, len(@date) - @point_ix) set @point_ix = charindex('.', @date) set @year_part = substring(@date, 0, @point_ix) set @datetime = @month_part + @day_part + @year_part + ' ' + @time return @datetime END 

当我运行它..我得到:消息241,级别16,状态1,行1转换date和/或时间从string转换失败。

Arghh!

那么,我该怎么办?

 ALTER FUNCTION [dbo].[ufn_GetDateTime] (@date nvarchar(11), @time nvarchar(11)) RETURNS nvarchar(22) AS BEGIN --select dbo.ufn_GetDateTime('25.03.2012.', '9:18:25') declare @day_part nvarchar(3) declare @point_ix int set @point_ix = charindex('.', @date) set @day_part = substring(@date, 0, @point_ix) return @day_part END 

我得到'25'。 所以,我一个人,所以我改变..

 set @day_part = substring(@date, 0, @point_ix + 1) 

瞧! 现在它工作:)