我创建了一个存储过程,必要时会INSERT / UPDATE。我正在使用此方法来评估是否必须插入:
INSERT INTO X
SELECT @A, @B, @C -- Exactly as the table, all nullables
WHERE NOT EXISTS (SELECT * from ... WHERE condition)
但我收到了
Msg 213,Level 16,State 1,Procedure ArtigoEAN_Remover,Line 48 [Batch Start Line 7] 列名或提供的值数与表定义不匹配。
这是我的完整代码(我发信号第48行):
@ArtigoID AS varchar(14),
@TipoArtigo AS varchar(3),
@CodBarras AS varchar(24)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
SET NOCOUNT ON;
IF (@ArtigoID IS NOT NULL AND @TipoArtigo IS NULL) OR (@ArtigoID IS NULL AND @TipoArtigo IS NOT NULL)
BEGIN
PRINT 'Tem que escolher ArtigoID & TipoArtigo para remover código EAN da referência.'
RETURN
END
--
IF (@CodBarras IS NOT NULL) AND (@ArtigoID IS NOT NULL OR @TipoArtigo IS NOT NULL)
BEGIN
PRINT 'Escolher Código EAN apenas (Para remover esse código de barras de todas as referências) OU ArtigoID + TipoArtigo (remover todos os códigos EAN associados a essa referência)'
RETURN
END
--
IF @ArtigoID IS NOT NULL AND @TipoArtigo IS NOT NULL
BEGIN
UPDATE [s].[dbo].[FArtigo]
SET CodBarras = ''
WHERE ArtigoID = @ArtigoID AND TipoArtigo = @TipoArtigo AND CodBarras = @CodBarras
-- LINE 48
INSERT INTO [s].[dbo].[Infolog_ArtigoEAN]
SELECT @ArtigoID,@TipoArtigo,@CodBarras
WHERE NOT EXISTS (SELECT * FROM [s].[dbo].[Infolog_ArtigoEAN] WHERE ArtigoID = @ArtigoID AND TipoArtigo = @TipoArtigo AND CodBarras = @CodBarras)
-- Inserts above if nox exist, update below in any case.
UPDATE [s].[dbo].[Infolog_ArtigoEAN] SET CodBarras = '' WHERE ArtigoID = @ArtigoID AND TipoArtigo = @TipoArtigo AND CodBarras = @CodBarras
INSERT INTO [s].[dbo].[ArtigoEAN]
SELECT @ArtigoID,@TipoArtigo,@CodBarras
WHERE NOT EXISTS (SELECT * FROM [s].[dbo].[Infolog_ArtigoEAN] WHERE ArtigoID = @ArtigoID AND TipoArtigo = @TipoArtigo AND CodBarras = @CodBarras)
UPDATE [s].[dbo].[ArtigoEAN] SET CodBarras = '' WHERE ArtigoID = @ArtigoID AND TipoArtigo = @TipoArtigo AND CodBarras = @CodBarras
END
--
IF @CodBarras IS NOT NULL AND (@ArtigoID IS NULL AND @TipoArtigo IS NULL)
BEGIN
UPDATE [s].[dbo].[FArtigo] SET CodBarras = '' WHERE CodBarras = @CodBarras
UPDATE [s].[dbo].[Infolog_ArtigoEAN] SET CodBarras = '' WHERE CodBarras = @CodBarras
UPDATE [s].[dbo].[ArtigoEAN] SET CodBarras = '' WHERE CodBarras = @CodBarras
END
END
所以我的问题是,为什么它在第48行之后尝试执行INSERT,当我只是改变(保存)过程时,我甚至没有使用参数运行它。
请记住,我想使用SELECT作为条件INSERT(INSERT INTO dbo.Example SELECT(to,insert,if,true)WHERE NOT EXISTS(SELECT * FROM dbo.Example WHERE myCondition = notExist)
答案 0 :(得分:0)
您收到此错误是因为表中的列数和您在insert语句中指定的值的数量不匹配。
在您的查询中,您提供了3个值,因此您的表中可能有超过3列或少于3列。
以避免将来出现此类错误,而不是指定
INSERT INTO TableName
VALUES(1,2,3)
指定要插入值的列名称。喜欢这个
INSERT INTO TableName(Col1,Col2,Col3)
VALUES(1,2,3)
或
INSERT INTO X(Col1,Col2,Col3)
SELECT @A, @B, @C
您不需要运行脚本/过程来获取错误,SQL Server将在编译时返回错误,即;当您尝试创建或更改过程时