以下查询是为 SQL Server 编写的,如果我硬编码@TempStaff
,那么它可以正常工作并且有一个值,@Tempstaff
但是这样的代码不会返回任何内容。
查询是收集员工级别及以下的所有员工:
DECLARE
@TempStaff varchar(10),
@staff_Full_name varchar (30)
BEGIN
SELECT @staff_Full_name = 'Doe, John'
DECLARE @staffNameTable TABLE
(
StaffID char(7),
StaffName Varchar(50)
)
INSERT INTO @staffNameTable
SELECT * FROM dbo.fn_Staff_Full_Name()
SELECT @TempStaff = (
SELECT StaffId
FROM @staffNameTable st
WHERE st.StaffName = @staff_Full_name
)
END
DECLARE @staff TABLE
(
StaffId char(10)
)
INSERT INTO @staff (StaffId)
SELECT * FROM dbo.fn_Supervisor_List(10, @TempStaff)`
功能是
ALTER FUNCTION [dbo].[fn_Supervisor_List]
(
@looptill Int,
@StaffId varchar(10)
)
RETURNS
@staff TABLE
(
StaffId char(10)
)
AS
BEGIN
DECLARE
@loop int
INSERT INTO @staff
SELECT s.StaffId
FROM Staff s with (nolock)
WHERE s.StaffId like @StaffId
BEGIN
SELECT @loop = 0
WHILE @loop < @looptill
BEGIN
INSERT INTO @staff
SELECT s.StaffId
FROM dbo.StaffSupervisors s with (nolock)
--WHERE s.super_id in (
WHERE s.SupervisorId in (
SELECT s2.StaffId
FROM @Staff s2
)
AND s.StaffId not in (
SELECT s2.StaffId
FROM @Staff s2
)
SELECT @loop = @loop + 1
END
END
RETURN
END
当我在填充后运行 SELECT @TempStaff 时 - 我得到了我期望的变量,但是当我最后运行 SELECT * FROM @Staff 时,@Staff 是空的。