我将从另一个表和我自己的值中选择的值插入到表中。在表中,插入了我插入自己的值的列。但是我从另一个表中插入选定值的列是null
。为什么?
我已将数据插入“EmployeeDeleteLog”表格,但在“EmployeeDeleteLog
”表格中,“IDdeleted
”和“DeleteDate
”列中包含数据。其他所有列都有“NULL
”值。
1.第1部分
create table Person
(
IdNo int primary key identity NOT NULL,
FirstName varchar(50) ,
LastName varchar(100),
Gender char(1) NOT NULL,
Nationality varchar(50),
Email varchar(100) UNIQUE,
Fax varchar(12) UNIQUE,
PostBox varchar(6),
Street varchar(60),
City varchar(60),
Province varchar(60),
Country varchar(100) NOT NULL
);
CREATE TABLE EmployeeDeleteLog(
IDdeleted int,
FirstName varchar(50) ,
LastName varchar(100),
DeleteDate date,
Email varchar(100),
Fax varchar(12),
PostBox varchar(6),
Street varchar(60),
City varchar(60),
Province varchar(60),
Country varchar(100)
)
2.Part 2
CREATE FUNCTION [dbo].[countIDs] (@EmpID AS INT)
RETURNS INT
AS
BEGIN
DECLARE @myCount AS INT
SELECT @myCount = COUNT(IdNo)
FROM Person
WHERE IdNo = @EmpID
RETURN @myCount
END
3.第3部分
CREATE PROCEDURE [dbo].[Employee_Delete](@EmpID int)
WITH EXECUTE AS CALLER
AS
BEGIN
IF [dbo].[countIDs](@EmpID) <> 1
BEGIN
RAISERROR ('ID does not exist', 1, 1)
RETURN 0
END
--check to see if update occured
--and return status
IF @@ROWCOUNT = 1
BEGIN
INSERT INTO EmployeeDeleteLog(IDdeleted,
FirstName,
LastName,
DeleteDate,
Email,
Fax,
PostBox,
Street,
City,
Province,
Country)
SELECT IDdeleted = IdNo,
FirstName,
LastName,
DeleteDate = GETDATE(),
Email,
Fax,
PostBox,
Street,
City,
Province,
Country
FROM Person
WHERE IdNo=@EmpID
--Attempt Delete
DELETE FROM [dbo].[Person]
WHERE IdNo = @EmpID
RETURN 1
END
ELSE
RETURN 0
END
GO
答案 0 :(得分:2)
删除时使用输出
https://docs.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql
简单示例:
DELETE FROM dbo.table1
OUTPUT DELETED.* INTO @MyTableVar
WHERE id = 4
在您的情况下,使用它,它可能包含错误
DELETE FROM [dbo].[Person]
OUTPUT
DELETED.IdNo,
DELETED.FirstName,
DELETED.LastName,
DeleteDate = GETDATE(),
DELETED.Email,
DELETED.Fax,
DELETED.PostBox,
DELETED.Street,
DELETED.City,
DELETED.Province,
DELETED.Country
INTO EmployeeDeleteLog(IDdeleted,
FirstName,
LastName,
DeleteDate,
Email,
Fax,
PostBox,
Street,
City,
Province,
Country)
WHERE IdNo = @EmpID
答案 1 :(得分:0)
我已经像这样改变了程序:
CREATE PROCEDURE [dbo]。[Employee_Delete](@ EmpID int) 如 BEGIN
IF [dbo].[countIDs](@EmpID) <> 1
BEGIN
RAISERROR ('ID does not exist', 1, 1)
RETURN 0
END
INSERT INTO EmployeeDeleteLog(IDdeleted,
FirstName,
LastName,
DeleteDate,
Email,
Fax,
PostBox,
Street,
City,
Province,
Country)
SELECT IDdeleted = IdNo,
FirstName,
LastName,
DeleteDate = GETDATE(),
Email,
Fax,
PostBox,
Street,
City,
Province,
Country
FROM Person
WHERE IdNo=@EmpID
--Attempt Delete
DELETE FROM [dbo].[Person]
WHERE IdNo = @EmpID
END
GO
完成!