我创建了一个存储过程,必要时将INSERT / UPDATE。我正在使用此方法来评估是否必须插入:
INSERT INTO X
SELECT @A, @B, @C -- Exactly as the table, all nullables
WHERE NOT EXISTS (SELECT * from ... WHERE condition)
但我收到了
消息213,级别16,状态1,过程ArtigoEAN_Remover,行48 [批处理开始行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)
您收到此错误,因为表中的列数和您在insert语句中指定的值的数量不匹配。
在您的查询中,您提供了3个值,因此您的表中可能有超过3列或少于3列。
为了避免将来出现这种错误,而不是指定
INSERT INTO TableName
VALUES(1,2,3)
指定y要插入值的列名称。像这样
INSERT INTO TableName(Col1,Col2,Col3)
VALUES(1,2,3)
要么
INSERT INTO X(Col1,Col2,Col3)
SELECT @A, @B, @C
您不需要运行脚本/过程来获取错误,SQL Server将在编译时返回错误,即;当您尝试创建或更改过程时