【问题标题】:Error Conversion failed when converting the nvarchar procedure转换 nvarchar 过程时错误转换失败
【发布时间】:2018-10-22 09:39:58
【问题描述】:

表格视图组

NO_induk  |  Gaji_bulan
-----------------------                     
200012    |      012017                                                   
200012    |      022017                      
200012    |      122017               
200006    |      012017           
200006    |      022017           
200006    |      122017              
2000AA    |      012017          
2000AA    |      022017          
2000AA    |      122017             

ALTER PROCEDURE [dbo].[prcgroup]

@no_induk1 nvarchar(50),

@no_induk2 nvarchar(50),

@bulan1 nvarchar(6),

@bulan2 nvarchar(6)

AS
BEGIN

DECLARE @cols  AS NVARCHAR(MAX)='';
DECLARE @query AS NVARCHAR(MAX)='';

SELECT @cols = @cols + QUOTENAME(gaji_bulan) + ',' FROM (select distinct gaji_bulan from tblgaji_detail ) as tmp order by gaji_bulan
select @cols = substring(@cols, 0, len(@cols))  

set @query = 
'SELECT * from 
(
    select no_induk,nama_pelamar,kodept,namapt,kodetp,ket, nilai_ahir, gaji_bulan from View_group where
    no_induk>='+@no_induk1+' and no_induk<='+@no_induk2+' 
    and gaji_bulan>='+@bulan1+' and gaji_bulan<='+@bulan2+' 

) src
pivot 
(
    max(nilai_ahir) for gaji_bulan in (' + @cols + ')
) piv'

execute(@query)
END

如果我像这样执行程序,它运行良好:

exec prcgroup '200006','200006','012017','122017'

如果我这样执行会出现问题:

exec prcgroup '200006','2000AA','012017','122017'

错误 消息 245,第 16 级,状态 1,第 1 行 将 nvarchar 值“2000AA”转换为数据类型 int 时转换失败。

我希望它会这样运行:

prcgroup '200006','2000AA','012017','122017'

【问题讨论】:

  • “NO_induk”列中的“2000AA”是什么意思?
  • 'no_induk' 列的数据类型是什么?

标签: sql-server


【解决方案1】:

您正在比较字符串,因此它必须由 SingleQuote(') 修饰。因此,在&gt;= 条件之后,您必须使用'''+@no_induk2+''' 而不是'+@no_induk2+'。 更新您的查询如下:

set @query = 
'SELECT * from 
(
    select no_induk,nama_pelamar,kodept,namapt,kodetp,ket, nilai_ahir, gaji_bulan from View_group where
    no_induk>='''+@no_induk1+''' and no_induk<='''+@no_induk2+''' 
    and gaji_bulan>='''+@bulan1+''' and gaji_bulan<='''+@bulan2+''' 

) src
pivot 
(
    max(nilai_ahir) for gaji_bulan in (''' + @cols + ''')
) piv'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-06
    • 2019-03-06
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多