我正在编写一些存储过程,以便将用于当前年份记录的表格中的数据传输到用于存储历史数据的表格。我目前正在研究的一个例子是典型的Master-Detail关系,其中明显需要在主记录之前处理细节记录。我写了一个简单的测试查询来收集一些示例记录,看看我是否正确编写了基本的sql。
DECLARE @cuttoffdate date = '31/03/2009'
SELECT
*
FROM Landings.LandingDetails
INNER JOIN Landings.LandingHeaders
ON Landings.LandingHeaders.LandingId = Landings.LandingDetails.LandingId
WHERE Landings.LandingHeaders.LandingDate1 <= @cuttoffdate
SELECT
*
FROM Landings.LandingHeaders
WHERE Landings.LandingHeaders.LandingDate1 <= @cuttoffdate
这可以产生并产生我期望的两组记录。但是,当我在存储过程中使用它时:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [HistoricalData].[TransferAllLandingInformation]
-- Add the parameters for the stored procedure here
@cutoffdate date
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO HistoricalData.HistoricalLandingDetails
SELECT
*
FROM Landings.LandingDetails
INNER JOIN Landings.LandingHeaders
ON Landings.LandingHeaders.LandingId = Landings.LandingDetails.LandingId
WHERE Landings.LandingHeaders.LandingDate1 <= @cutoffdate
INSERT INTO HistoricalData.HistoricalLandingHeaders
SELECT
*
FROM Landings.LandingHeaders
WHERE Landings.LandingHeaders.LandingDate1 <= @cutoffdate
END
GO
无法执行,给我以下错误:
Msg 213,Level 16,State 1,Procedure TransferAllLandingInformation,Line 12 列名或提供的值数与表定义不匹配。
第12行就在BEGIN声明之后。
有人可以告诉我为什么会这样。我绝不会声称能够流利使用sql,结果这个特殊的错误让我目前难以理解,我想从中学习。
为了清楚起见,这是在SSMS 2012中撰写的。
由于
答案 0 :(得分:4)
错误消息表明您在HistoricalLandingDetails中的列数与您的select查询返回的结果不同,该查询包含来自HistoricalLandingDetails和LandingHeaders的所有数据。
我建议在插入和select中指定列,以确保所有内容都匹配,例如
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [HistoricalData].[TransferAllLandingInformation]
-- Add the parameters for the stored procedure here
@cutoffdate date
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO HistoricalData.HistoricalLandingDetails (cola, colb, colc)
SELECT
ld.cola, ld.colb, ld.colc
FROM Landings.LandingDetails ld
INNER JOIN Landings.LandingHeaders lh
...
答案 1 :(得分:2)
它们没有相同的结构。
在查询中,您只是选择这些语句才有效。但是在过程中,insert语句失败。
目标表中的列数或Insert语句中指定的列数和Insert语句中提供的值不匹配。
答案 2 :(得分:1)
由于错误建议您尝试在目标表中插入比列数更多的值。要明确地修改该类型的列名称,例如:
INSERT INTO HistoricalData.HistoricalLandingHeaders (col1, col2)
SELECT Landings.LandingHeaders.val1, Landings.LandingHeaders.val2
FROM Landings.LandingHeaders
WHERE Landings.LandingHeaders.LandingDate1 <= @cutoffdate