SQL - 如何使用 INSERTed table 中的值
SQL - How to use a value from INSERTed table
我正在尝试在我的数据库中插入一个新的位置记录...然后在稍后的 select 语句的 where 子句中重用新创建的 id 的值。
但是我遇到语法错误。
代码:
USE Widgets;
GO
DECLARE @userPrincipalName VARCHAR(100),
@displayName VARCHAR(100),
@domainName VARCHAR(100),
@locationId INT,
@uname VARCHAR(100);
DECLARE @newLocationId TABLE (
id INT
);
-- CREATE NEW LOCATION, FLAG AS PRIMARY
IF NOT EXISTS (SELECT *
FROM Locations
WHERE LocationName = 'outer-space')
BEGIN
INSERT INTO Locations
OUTPUT Inserted.ID INTO @newLocationId
SELECT 'out-space' ,'the final frontier', 60, 1
END
-- MUCH LATER IN THE SQL CODE:
IF NOT EXISTS (SELECT *
FROM LocationEnvironment
WHERE LocationId = @newLocationId.id
)
BEGIN
INSERT INTO LocationEnvironment
SELECT 1, id
FROM @newLocationId
END
错误是“必须声明标量变量”,它死于 SELECT 语句中的 WHERE 子句。
我也试过这样的:
IF NOT EXISTS (SELECT *
FROM LocationEnvironment
WHERE LocationId = id
FROM @newLocationId
)
但这也不管用。
如有任何提示,我们将不胜感激。
在 -- MUCH LATER IN THE SQL CODE:
之前添加 GO
语句
这会将上述语句发送到服务器。
我认为您需要将 SQL 代码部分中的 WHERE 子句从临时 table:
更新为 select
WHERE LocationId = @newLocationId.id
应该是:
WHERE LocationId = (select top 1 id from @newLocationId)
或者如果您的 table 变量中可能有多个值:
WHERE LocationId in (select id from @newLocationId)
我正在尝试在我的数据库中插入一个新的位置记录...然后在稍后的 select 语句的 where 子句中重用新创建的 id 的值。 但是我遇到语法错误。
代码:
USE Widgets;
GO
DECLARE @userPrincipalName VARCHAR(100),
@displayName VARCHAR(100),
@domainName VARCHAR(100),
@locationId INT,
@uname VARCHAR(100);
DECLARE @newLocationId TABLE (
id INT
);
-- CREATE NEW LOCATION, FLAG AS PRIMARY
IF NOT EXISTS (SELECT *
FROM Locations
WHERE LocationName = 'outer-space')
BEGIN
INSERT INTO Locations
OUTPUT Inserted.ID INTO @newLocationId
SELECT 'out-space' ,'the final frontier', 60, 1
END
-- MUCH LATER IN THE SQL CODE:
IF NOT EXISTS (SELECT *
FROM LocationEnvironment
WHERE LocationId = @newLocationId.id
)
BEGIN
INSERT INTO LocationEnvironment
SELECT 1, id
FROM @newLocationId
END
错误是“必须声明标量变量”,它死于 SELECT 语句中的 WHERE 子句。
我也试过这样的:
IF NOT EXISTS (SELECT *
FROM LocationEnvironment
WHERE LocationId = id
FROM @newLocationId
)
但这也不管用。 如有任何提示,我们将不胜感激。
在 -- MUCH LATER IN THE SQL CODE:
GO
语句
这会将上述语句发送到服务器。
我认为您需要将 SQL 代码部分中的 WHERE 子句从临时 table:
更新为 selectWHERE LocationId = @newLocationId.id
应该是:
WHERE LocationId = (select top 1 id from @newLocationId)
或者如果您的 table 变量中可能有多个值:
WHERE LocationId in (select id from @newLocationId)