如何使用加载了数据的用户定义表,插入表中,但其中一个表字段不会使用用户定义表中的数据。我想要一个标量变量取而代之。
@dataTableType
是以下用户定义的表:
CREATE TYPE [dbo].[NewSequenceType] AS TABLE (
[FK_Sequence] [int] NULL,
[FK_Status] [int] NULL,
[FK_Shift] [int] NULL,
[PK_SequenceType] [int] NULL,
[TypeName] [varchar](30) NULL,
[SequenceName] [varchar](100) NULL,
[SequenceDetails] [varchar](400) NULL,
[SequenceStatus] [varchar](15) NULL,
[SequenceShift] [varchar](15) NULL,
[EmployeeId] [varchar](8) NULL,
[EquipmentId] [varchar](25) NULL,
[Comments] [varchar](512) NULL,
[EnteredDate] [datetime] NULL
)
我的存储过程:
ALTER PROCEDURE [dbo].[spNewInspectionEntry] (@dataTableType NewSequenceType READONLY)
INSERT INTO dbo.PIT_Inspection (FK_Sequence, FK_Status, FK_Shift, FK_EmployeeName, FK_EquipmentName, Comments, EnteredDate)
SELECT
FK_Sequence, FK_Status, FK_Shift, EmployeeId,
EquipmentId, Comments, EnteredDate
FROM
@dataTableType;
我想做什么:
DECLARE @EmployeeIDExists varchar(8);
--Note that I only care about one row, this is Ok.
SELECT TOP 1 @EmployeeIDExists = EmployeeId FROM @dataTableType;
--Retrieve PKEmployeeId
SELECT @EmployeeIdPK = PK_EmployeeName
FROM dbo.PIT_EmployeeName
WHERE EmployeeId = @EmployeeIDExists
--Now I need to insert the value of @EmployeeIdPK? Along with the rest, it needs to replace EmployeeID and EquipmentId, Not sure how to...
INSERT INTO dbo.PIT_Inspection (FK_Sequence, FK_Status, FK_Shift, FK_EmployeeName, FK_EquipmentName, Comments, EnteredDate)
SELECT
FK_Sequence, FK_Status, FK_Shift, EmployeeId,
EquipmentId, Comments, EnteredDate
FROM
@dataTableType;
我怎样才能获得@EmployeeIdPK
和其他内容一样,需要替换EmployeeID
,我不希望用户定义的表中的EmployeeId
去那里,我想要变量@EmployeeIdPK
而不是。
答案 0 :(得分:1)
您可以在SELECT
列表中放置任何表达式,变量和文字值。请记住,所有行将重复这些值。
含义:
SELECT Field1,
Field2,
'hello' AS [LiteralText],
5 AS [LiteralNumber],
@Variable AS [ValueFromVariable]
FROM TableName;
将为所有行重复这些文字和变量值。
因此:
INSERT INTO dbo.PIT_Inspection (FK_Sequence, FK_Status, FK_Shift, FK_EmployeeName,
FK_EquipmentName, Comments, EnteredDate)
SELECT
FK_Sequence, FK_Status, FK_Shift, @EmployeeIdPK,
EquipmentId, Comments, EnteredDate
FROM
@dataTableType;