我试图获取插入记录的行号,以便我可以将它用于select语句。我想要完成的是将一个人插入一个表中,获取该行号,然后从另一个表中选择与行号匹配的内容。这是我到目前为止所得到的:
INSERT INTO TableA Values (‘Person’)
Select timeToken
From
(
Select
Row_Number() Over (Order By tokenOrder) As RowNum
, *
From TableB WHERE taken = false
) t2
Where RowNum = (Row Number of Inserted Item)
如何获取插入项目的行号,我想比较ID,因为某些记录可能已被删除,因此它们不匹配。
TABLEA Data (primary key is id)
id name
3 John
12 Steve
TABLEB Data (primary key is id)
id timeToken tokenOrder taken
2 1:00am 1 false
3 2:00am 2 false
5 3:00am 3 true
6 4:00am 4 false
当我插入人物时,我期待的结果,选择参加将返回凌晨4点
我在存储过程中执行此操作。
答案 0 :(得分:3)
ORDER BY
子句,否则认为行包含数字是错误的。答案 1 :(得分:0)
根据它的声音,您正尝试执行以下链接中列出的内容LINK - SQL Server - Return value after INSERT
基本上:
def flatten(d):
es = [d.pop(k) for k in sorted(d) if isinstance(d[k], dict)]
# Due to sorted the dictionaries those keys that are lexicographically after
# will overwrite the key-value pairs from those that are before.
# One would expect that `d.update(*es)` would work
# but it doesn't as `update` only takes one argument.
for e in es:
d.update(e)
def flatten_many(d):
while any(isinstance(d[k], dict) for k in d):
flatten(d)
答案 2 :(得分:0)
试试这个。它可以帮到你
Declare @TableA_PK BIGINT
INSERT INTO TableA Values ('Person')
SET @TableA_PK=SCOPE_IDENTITY()
Select timeToken
From
(
Select
Row_Number() Over (Order By tokenOrder) As RowNum
, *
From TableB WHERE taken = false
) t2
Where RowNum =@TableA_PK
SCOPE_IDENTITY():范围标识将捕获最后插入的记录主键值,并且可以存储在变量和 然后它可以进一步重复使用
答案 3 :(得分:0)
在表b中添加外键约束(在表A中引用主键)将是好的,因为您将无法从表A中删除记录而不从表B中删除它们。这将有助于比较使用ID的记录。
答案 4 :(得分:0)
试试这个
declare @rowNum int;
INSERT INTO TableA Values ('Person')
SET @rowNum =SCOPE_IDENTITY()
select * from TableA where id = @rowNum