使用SELECT结果作为INSERT INTO VALUES显示CLR类型错误

时间:2011-05-12 06:27:03

标签: c# asp.net sql

我正在尝试在VS Query Builder中执行此SQL命令:

INSERT INTO DATA_TEMP (ITEM, Q1, Q2, Q3, Q4, TOTAL)
SELECT DISTINCT
    DATA_2.ITEM,
    (SELECT AMOUNT AS Expr1
     FROM DATA
     WHERE (QTR = 1) AND (DATA_2.ITEM = ITEM) AND (FY = @fy)
       AND (BU = @bu) AND (PERIOD = @per)) AS Q1,
    (SELECT AMOUNT AS Expr1
     FROM DATA AS DATA_3
     WHERE (QTR = 2) AND (DATA_2.ITEM = ITEM) AND (FY = @fy)
       AND (BU = @bu) AND (PERIOD = @per)) AS Q2,
    (SELECT AMOUNT AS Expr1
     FROM DATA AS DATA_3
     WHERE (QTR = 3) AND (DATA_2.ITEM = ITEM) AND (FY = @fy)
       AND (BU = @bu) AND (PERIOD = @per)) AS Q3,
    (SELECT AMOUNT AS Expr1
     FROM DATA AS DATA_3
     WHERE (QTR = 4) AND (DATA_2.ITEM = ITEM) AND (FY = @fy)
       AND (BU = @bu) AND (PERIOD = @per)) AS Q4,
    (SELECT SUM(AMOUNT) AS Expr1
     FROM DATA AS DATA_3
     WHERE (DATA_2.ITEM = ITEM) AND (FY = @fy) AND (BU = @bu)
       AND (PERIOD = @per)) AS Total
FROM DATA AS DATA_2 INNER JOIN
     DATA AS DATA_1 ON DATA_2.ID = DATA_1.ID
WHERE (DATA_2.ITEM = @item)

给我这个错误:

  

错误源:.Net SqlClient数据提供程序错误消息:参数3   ([C:\ test.MDF]。[]。[未知]):CLR类型不存在或者你做   没有权限访问它。

奇怪的是,当我单独执行SELECT和INSERT INTO命令时,它工作正常。顺便编译网站时它也有效。

但是在使用存储过程时它不起作用,这就是为什么我想知道导致这种情况的原因。

2 个答案:

答案 0 :(得分:2)

问题很可能是由于解析问题造成的。

尝试将以下内容添加到最终的WHERE子句中:

WHERE (DATA_2.ITEM = @item) AND (@fy = @fy) AND (@bu = @bu) AND (@per = @per)

我怀疑它会挂在代码的SELECT部分​​中的参数中,这些参数未在最终的where子句中定义。

答案 1 :(得分:1)

您可以更简单地编写此查询:

Insert DATA_TEMP( ITEM, Q1, Q2, Q3, Q4, TOTAL )
Select D2.ITEM
    , Min( Case When QTR = 1 Then D1.AMOUNT End ) As Q1
    , Min( Case When QTR = 2 Then D1.AMOUNT End ) As Q2
    , Min( Case When QTR = 3 Then D1.AMOUNT End ) As Q3
    , Min( Case When QTR = 4 Then D1.AMOUNT End ) As Q4
    , Sum( AMOUNT ) As Total
From DATA As D1
    Join DATA_2 As D2
        On D2.ID = D1.ID
Where ITEM = @item
    And FY = @fy
    And BU = @bu
    And PERIOD = @per
Group By D2.ITEM

当然,这并不能解决您的CLR问题,但可能会使测试更简单。