如何在SQL Update上获取主键?

时间:2015-01-08 19:54:16

标签: sql tsql primary-key

如果" searchWord"我正在更新表格。找到了。如果找到了,我想知道我刚刚更新的记录的主键是什么。我该怎么做?以下是我的代码。另一方面,如果" searchWord"找不到我插入它并使用scope_identity()来获取它。我的问题是如何使用Update做同样的事情?我想我可以先做一个select语句,但这是一个额外的查询。

BEGIN TRAN    
    UPDATE COBC_searchedWord 
    SET searchCount=searchCount+1, 
        resultsReturned=#resultsReturned#, 
        lastSearched=getDate() 
    WHERE searchedWord='#searchedWord#';

    IF @@ROWCOUNT = 0
    BEGIN
        INSERT INTO COBC_searchedWord
            ([searchedWord] ,[searchCount] ,[resultsReturned] ,[lastSearched])
        VALUES
            ('#searchedWord#',1,'#resultsReturned#',getDate())
        SELECT scope_identity() AS searchedWordID
    END
COMMIT TRAN

更新:这是我最终的结果,似乎有效。感谢您的投入。

DECLARE @tmpTable TABLE (ID int);  
UPDATE COBC_searchedWord
SET searchCount=searchCount+1, 
    resultsReturned=#resultsReturned#, 
    lastSearched=getDate()  
OUTPUT inserted.searchedWordID into @tmpTable          
WHERE searchedWord='#searchedWord#';          

IF @@ROWCOUNT = 0  
BEGIN  
    INSERT INTO COBC_searchedWord  
        ([searchedWord])         
        OUTPUT inserted.searchedWordID into @tmpTable  
    VALUES  
        ('#searchedWord#');  
END  
SELECT ID from @tmpTable;

2 个答案:

答案 0 :(得分:5)

您应该使用OUTPUT子句。在线书籍将解释如何。

答案 1 :(得分:0)

试试这个,如果你要更新你的记录,那个搜索词会集中在表格中然后从表格中选择searchWordID

BEGIN TRAN    
    UPDATE COBC_searchedWord 
    SET searchCount=searchCount+1, 
        resultsReturned=#resultsReturned#, 
        lastSearched=getDate() 
    WHERE searchedWord='#searchedWord#';

    IF @@ROWCOUNT = 0
    BEGIN
        INSERT INTO COBC_searchedWord
            ([searchedWord] ,[searchCount] ,[resultsReturned] ,[lastSearched])
        VALUES
            ('#searchedWord#',1,'#resultsReturned#',getDate())
        SELECT scope_identity() AS searchedWordID
    END
    ELSE
    BEGIN
      SELECT searchedWordID FROM COBC_searchedWord 
      WHERE searchedWord='#searchedWord#';
    END
COMMIT TRAN