我在sql server 2012上工作;在构建动态查询时,我遇到以下错误
消息8114,16级,状态5,第16行
将数据类型varchar转换为float时出错
如何解决这个错误?
我构建了一个基于 @Header
以及 @column
以及 @Body
. @Header
表示必须显示为标头的标头。 @column
表示数据透视列。 @Body
表示数据的select查询。
CREATE TABLE #FinalTable
(
PART_ID nvarchar(50) ,
CompanyName nvarchar(50),
PartNumber nvarchar(50),
DKFeatureName nvarchar(100),
value float,
StatusId int,
DisplayOrder int,
splitFlag bit
)
INSERT INTO #FinalTable
VALUES
('1222', 'Honda', 'silicon', 'package', '15.50Am', 2, 5, 0),
('1900', 'MERCEIS', 'GLASS', 'family', '90.00Am', 2, 2, 1),--have column per Unit on @Header because FlagAllow=1
('5000', 'TOYOTA', 'alominia', 'source', '70.20kg', 2, 1, 0),
('8000', 'MACDA', 'motor', 'parametric', '50.40kg', 2, 3, 1),--have column per Unit on @Header because FlagAllow=1
('8900', 'JEB', 'mirror', 'noparametric', '75.35kg', 2, 4, 0)
DECLARE @Header NVARCHAR(MAX)
SELECT
@Header = STUFF((SELECT ', ' + CASE WHEN A.splitFlag = 1 AND a.value <> '-' AND (a.Value IS NOT NULL) THEN '''' + A.DKFeatureName + ''' AS '' '+ A.DKFeatureName + ''', ''' + A.DKFeatureName + 'Units' + ''' AS ''' + A.DKFeatureName +'Units' +'''' else ''''+A.DKFeatureName +''' as ''' + A.DKFeatureName +'''' END
FROM #FinalTable A
WHERE StatusId = 2
ORDER BY DisplayOrder
FOR XML PATH ('')), 1, 2, '')
DECLARE @Columns NVARCHAR(MAX)
SELECT
@Columns = STUFF(
(
SELECT ', ' + case when A.splitFlag = 1 and a.value<> '-' and (a.Value is not null) then '['+A.DKFeatureName+'],['+A.DKFeatureName+'Unit]' else quotename(A.DKFeatureName) end
FROM #FinalTable A where StatusId=2
ORDER BY DisplayOrder
FOR XML PATH ('')
),1,2,''
)
DECLARE @Body NVARCHAR(MAX)
SELECT
@Body = STUFF(
(
SELECT ', ' + case when A.splitFlag = 1 and a.value<> '-' and (a.Value is not null) then 'LEFT(' + QUOTENAME (A.DKFeatureName) + ',PATINDEX(''%[^0-9.]%'',' + QUOTENAME (A.DKFeatureName) + '+ ' + ''' ''' + ')-1) as ['+A.DKFeatureName+'],RIGHT('+ QUOTENAME (A.DKFeatureName) +',LEN('+ QUOTENAME (A.DKFeatureName) +') - PATINDEX(''%[^0-9.]%'','+ QUOTENAME (A.DKFeatureName) +')+1) as ['+A.DKFeatureName +'Units'+']' else quotename(A.DKFeatureName) end
FROM #FinalTable A
where StatusId=2
ORDER BY A.DisplayOrder
FOR XML PATH ('')
),1,2,''
)
DECLARE @SQL NVARCHAR(MAX)
select @SQL =CONCAT('
SELECT * Into #NewTable
FROM #FinalTable
PIVOT(max(Value) FOR DKFeatureName IN ('+@Columns+')) AS PVTTable
',
N' Select ''PART_ID'' as ''PART_ID'' ,''CompanyName'' as ''CompanyName'',''PartNumber'' as ''PartNumber'' , ' +@Header + '
union all
select PART_ID,CompanyName,PartNumber, ' +@Body + ' from #NewTable
')
EXEC (@SQL)
1条答案
按热度按时间a1o7rhls1#
您使用的列值是float,它是一个数字,而不是varchar。但是输入varchar=“15.50am”。
可以为单位(am、kg等)创建新列
或者可以更改值,如数值(5,2)