我正在尝试创建一个返回带有一堆字段的表的函数。 函数中使用的查询将数据插入临时表,然后临时表插入到返回表中。 当我在函数外部运行它时查询运行正常,但是当我从函数中选择时,我得到“将数据类型nvarchar转换为数字时出错”。错误。
返回表的结构与选择并插入返回表的表相同。以下是函数的定义方式
ALTER FUNCTION [dbo].[Func_PrescriberData](@NetworkID Bigint, @StartDate datetime, @EndDate datetime)
RETURNS @rtnTable TABLE
(
Name nvarchar(1000) null,ClinicID int null ,NetworkPrescriberID int Null,GuideMedPatients int NULL, InactivePatients int NULL,AvgAge decimal NULL,AvgPHQScore decimal NULL,
[%RiskAssessmentHigh] varchar(10) NULL ,[%RiskAssessmentModerate] varchar(10) NULL,[%RiskAssessmentLow] varchar(10) NULL,
ToxicologyTests int NULL,[%ConsistentResults] varchar(10) NULL, [%Alcohol] varchar(10) NULL,[%NegativePrescribed] varchar(10) NULL
,[%Illicit] varchar(10) NULL,TotalPDMPs int NULL,[%AberrantResults] varchar(10) NULL, CSAReviewed int NULL,Type nvarchar(1000) null ,medlesstan15 int NULL,between15and59 int NULL,between60and100 int NULL,between101and500 int NULL,greaterthan500 int NULL, avgmed decimal NULL, [BH/AM] int NULL,OpiodsBelowThreshold int NULL,OpioidPreScreening int NULL,SedativesAntiAnxiety int NULL,Stimulants int NULL,Other int NULL)
AS
BEGIN
DECLARE @TempTable table
(
Name nvarchar(1000) null,ClinicID int null ,NetworkPrescriberID int Null,GuideMedPatients int NULL, InactivePatients int NULL,AvgAge decimal NULL,AvgPHQScore decimal NULL,
[%RiskAssessmentHigh] varchar(10) NULL ,[%RiskAssessmentModerate] varchar(10) NULL,[%RiskAssessmentLow] varchar(10) NULL,
ToxicologyTests int NULL,[%ConsistentResults] varchar(10) NULL, [%Alcohol] varchar(10) NULL,[%NegativePrescribed] varchar(10) NULL
,[%Illicit] varchar(10) NULL,TotalPDMPs int NULL,[%AberrantResults] varchar(10) NULL, CSAReviewed int NULL,Type nvarchar(1000) null ,medlesstan15 int NULL,between15and59 int NULL,between60and100 int NULL,between101and500 int NULL,greaterthan500 int NULL, avgmed decimal NULL, [BH/AM] int NULL,OpiodsBelowThreshold int NULL,OpioidPreScreening int NULL,SedativesAntiAnxiety int NULL,Stimulants int NULL,Other int NULL)
insert into @TempTable (
Name ,ClinicID,NetworkPrescriberID,GuideMedPatients, InactivePatients ,AvgAge ,AvgPHQScore ,[%RiskAssessmentHigh],[%RiskAssessmentModerate] ,[%RiskAssessmentLow]
,ToxicologyTests ,[%ConsistentResults], [%Alcohol] ,[%NegativePrescribed] ,[%Illicit],TotalPDMPs ,[%AberrantResults],
CSAReviewed ,Type,medlesstan15,between15and59,between60and100,between101and500,greaterthan500,avgmed,[BH/AM],OpiodsBelowThreshold,OpioidPreScreening,SedativesAntiAnxiety,Stimulants,Other
可能很难说出上述脚本的问题是什么,但我正在寻找一种方法来调试问题所在。 奇怪的是,如果我更改其中一个应该以相同格式返回数据的参数(更改NetworkID),该函数运行正常。
有人可以帮我指出去哪儿吗?
谢谢,
我找到了发布整个sql脚本的链接。可以找到here
答案 0 :(得分:1)
检查将插入decimal
列的所有列,在您的示例中AvgAge
和AvgPHQScore
我猜测原始nvarchar
列中有空格或特殊字符,这会给您带来错误。
最简单的检查方法是尝试找到哪两列映射到AvgAge
和AvgPHQScore
,然后运行以下语句来检查nvarchar
列中的所有值可以隐式转换为decimal
:
SELECT original_nvarchar_column
FROM TABLE
WHERE ISNUMERIC(original_nvarchar_column) = 0
如果有任何返回,则表示该nvarchar
列中的所有值都不能转换为decimal
,这将导致您遇到的问题。