将数据类型varchar转换为数字动态数据透视时出错

时间:2016-11-14 20:04:46

标签: sql sql-server

我收到标题中描述的错误,我的代码如下所示:

declare
@cols numeric(10,0),
@sql numeric(10,0)

select @cols = isnull(@cols + ', ', '') + '[' + T.AmountPayd + ']' from (select distinct AmountPayd from t1) as T

select @sql = '
    select *
    from t1 as T
        pivot
        (
            sum(T.AmountPayd) for T.Customer in (' + @cols + ')
            ) as P'
exec sp_executesql @sql = @sql

此行发生错误:

select @cols = isnull(@cols + ', ', '') + '[' + T.AmountPayd + ']' from (select distinct AmountPayd from t1) as T

在我的表格中,AmountPayd被声明为数字数据类型。 我得到的错误是:

  

Msg 8114,Level 16,State 5,Line 108转换数据类型时出错   varchar为数字。

2 个答案:

答案 0 :(得分:1)

您已将@cols声明为数字(10,0),但您正在尝试为其指定文本 可能需要将其声明为nvarchar(max)。

P.S。 通过连接AmountPayd你想得到一个客户列表?

答案 1 :(得分:1)

declare
--@cols numeric(10,0),
--@sql numeric(10,0)
@cols varchar(max),
@sql varchar(max)

--Here you are setting @cols to a concatenated list of the amounts in your table
--The problem is you are trying to concat a decimal or integer into a string without casting it
--This is the same as doing 'A' + 1 and wanting to get A1. You first have to cast it.
--Notice the CAST(T.AmountPayd AS VARCHAR). But cols still needs to be a varchar in your declaration.

select @cols = isnull(@cols + ', ', '') + '[' + CAST(T.AmountPayd AS VARCHAR) + ']' from (select distinct AmountPayd from t1) as T

--Here you are building your dynamic SQL, which is a string which is why @sql must be varchar or nvarchar
select @sql = '
    select *
    from t1 as T
        pivot
        (
            sum(T.AmountPayd) for T.Customer in (' + @cols + ')
            ) as P'
exec sp_executesql @sql = @sql

您几乎已将此示例行复制为行,您只是错过了变量的声明。

http://sqlhints.com/2014/03/18/dynamic-pivot-in-sql-server/