如何在删除具有相同主键的行后将数据插入表中?

时间:2017-01-13 04:31:28

标签: sql-server stored-procedures

我有一个存储过程来更新单独表中的记录。对于此任务,首先我删除与该主键相关的所有记录。然后运行插入查询。但是当我这样做时,我在SQL Server中收到错误。

这是存储过程

ALTER PROCEDURE [dbo].[update_HS_HR_LANG]
    @appNo Int,
    @LCODE VARCHAR(30),
    @ABILITY int
AS
BEGIN
    DELETE FROM [HS_HR_LANG]
    WHERE App_no = @appNo
END
BEGIN
    INSERT INTO [HS_HR_LANG] ([App_no], [lang_code], [ability_type])
    VALUES (@appNo, @LCODE, @ABILITY)
END                              

这是我得到的错误

  

必须声明标量变量“@appNo”

2 个答案:

答案 0 :(得分:1)

您的存储过程在此处结束:

ALTER PROCEDURE [dbo].[update_HS_HR_LANG]
@appNo Int,
@LCODE VARCHAR(30),
@ABILITY int

AS

BEGIN

DELETE 
FROM [HS_HR_LANG]
WHERE App_no=@appNo

END -- <-----HERE

然后,您稍后访问@appNo,以便收到错误。

因此,你应该改为:

ALTER PROCEDURE [dbo].[update_HS_HR_LANG]
@appNo Int,
@LCODE VARCHAR(30),
@ABILITY int

AS

BEGIN -- <----- START

DELETE 
FROM [HS_HR_LANG]
WHERE App_no=@appNo

insert into [HS_HR_LANG]
([App_no]
,[lang_code]
,[ability_type])
 VALUES
       (@appNo,
        @LCODE,
        @ABILITY)
END  -- <----- END

答案 1 :(得分:0)

ALTER PROCEDURE [dbo].[update_HS_HR_LANG]
 @appNo Int,
 @LCODE VARCHAR(30),
 @ABILITY int

 AS

 BEGIN --<--start begin from here and remove the begin,end in the middle---

 DELETE 
 FROM [HS_HR_LANG]
 WHERE App_no=@appNo

 insert into [HS_HR_LANG]
 ([App_no]
,[lang_code]
,[ability_type])
 VALUES
   (@appNo,
    @LCODE,
    @ABILITY)
    END  -- <---------