我是SQL界的新手,但已经开发了很多年。我收到一个非常令人困惑的错误。我将最后一个UNION ALL SELECT(带有ncr_actual_dev的那个)添加到SELECT语句中,只有在声明了表时才会导致错误。如果我单独运行整个SELECT语句( BOLD 中的部分),则完成后没有任何问题。或者,如果我像第二个例子那样运行它,没有错误。我错过了什么?
DECLARE @table TABLE (prod_code varchar(10),
Stage varchar(10),
Stage_Date date)
INSERT INTO @table
SELECT product_code, 'PLAN' AS Stage, ncr_actual_plan AS Stage_Date
FROM ip.product_custom_data
WHERE ncr_actual_plan IS NOT NULL
UNION ALL SELECT product_code, 'CD' AS Stage, ncr_actual_cd
FROM ip.product_custom_data
WHERE ncr_actual_cd IS NOT NULL
UNION ALL SELECT product_code, 'CCA' AS Stage, ncr_actual_cca
FROM ip.product_custom_data
WHERE ncr_actual_cca IS NOT NULL
UNION ALL SELECT product_code, 'CONCEPT' AS Stage, ncr_actual_concept
FROM ip.product_custom_data
WHERE ncr_actual_concept IS NOT NULL
UNION ALL SELECT product_code, 'DEVELOPMENT' AS Stage, ncr_actual_dev
FROM ip.product_custom_data
WHERE ncr_actual_dev IS NOT NULL
DECLARE @table TABLE (prod_code varchar(10),
Stage varchar(10),
Stage_Date date)
SELECT product_code, 'DEVELOPMENT' AS Stage, ncr_actual_dev
FROM ip.product_custom_data
WHERE ncr_actual_dev IS NOT NULL
答案 0 :(得分:2)
使用:
DECLARE @table TABLE (prod_code varchar(100), Stage varchar(100), Stage_Date date) ...
'DEVELOPMENT' AS Stage
有11个字符,您已尝试插入列Stage varchar(10)
。
或者你可以使用临时表和SELECT INTO
之类的:
SELECT product_code, 'PLAN' AS Stage, ncr_actual_plan AS Stage_Date
INTO #table
FROM ip.product_custom_data
WHERE ncr_actual_plan IS NOT NULL
UNION ALL SELECT product_code, 'CD' AS Stage, ncr_actual_cd
FROM ip.product_custom_data
WHERE ncr_actual_cd IS NOT NULL
UNION ALL SELECT product_code, 'CCA' AS Stage, ncr_actual_cca
FROM ip.product_custom_data
WHERE ncr_actual_cca IS NOT NULL
UNION ALL SELECT product_code, 'CONCEPT' AS Stage, ncr_actual_concept
FROM ip.product_custom_data
WHERE ncr_actual_concept IS NOT NULL
UNION ALL SELECT product_code, 'DEVELOPMENT' AS Stage, ncr_actual_dev
FROM ip.product_custom_data
WHERE ncr_actual_dev IS NOT NULL;
SELECT *
FROM #table;