2010-05-25 24 views
15

Desidero aggiornare una riga nel mio data base. Il problema è che, attraverso un errore da parte mia, ho due file di dati identici. Come posso eseguire l'aggiornamento su una sola riga?Aggiornare una riga singola con t-sql

risposta

12

Spesso tabelle hanno un ID univoco. E dovresti filtrare su quello.

Per esempio,

UPDATE YourTable 
SET YourColumnToUpdate = 'your_value' 
WHERE YourUniqueColumn = @Id 

Se la tabella non dispone di un ID univoco, considerare l'aggiunta di uno: una colonna integer con un Primary Key e Identity.

0

Utilizzare SET ROWCOUNT;

SET ROWCOUNT 1; UPDATE Production.ProductInventory SET Quantity = 400 WHERE Quantità < 300; GO

http://msdn.microsoft.com/en-us/library/ms188774.aspx

+0

"Uso SET ROWCOUNT non influenzerà DELETE, INSERT e UPDATE nella prossima versione di SQL Server. Non utilizzare SET ROWCOUNT con, INSERT e UPDATE DELETE in nuovo progetto di sviluppo e pianifica di modificare le applicazioni che attualmente lo utilizzano.Per ulteriori informazioni, vedere DELETE (Transact-SQL) per le istruzioni DELETE, INSERT e UPDATE che attualmente utilizzano SET ROWCOUNT, si consiglia di riscriverle per utilizzare la sintassi TOP. , INSERT (Transact-SQL) o UPDATE (Transact-SQL). " –

+0

Nice Francisco, è molto importante sapere! Grazie! –

21

In SQL Server 2005 +, è possibile utilizzare

UPDATE TOP (1) .... 

Il vantaggio di questo corso SET ROWCOUNT è che qualsiasi trigger non saranno soggetti ad un limite ROWCOUNT, che è quasi certamente una buona cosa.

+0

_ (ad es. _ 'UPDATE TOP (1) TABLE_NAME SET COLUMN_NAME = 'TOP 1'' –

3

Ti suggerisco di tornare indietro e normalizzare il tuo database. Per lo meno aggiungi una colonna di chiave primaria int incremento automatico e usa quell'id. Usando UPDATE TOP 1 potrebbe funzionare e rispondere direttamente alla tua domanda, ma la non normalizzazione del tuo database è il problema "reale".

http://en.wikipedia.org/wiki/Database_normalization

0
-- 01. create the table for the test-data 
CREATE TABLE dbo.Orders (
    ID INTEGER 
    ,Value DECIMAL(10, 2) 
    ,Descr NVARCHAR(100) 
    ,BookingDate DATETIME 
    ,UserName NVARCHAR(100) 
    ,CountMeasure INTEGER 
) 

-- 02. save the timestamp for the inserts 
DECLARE @date AS DATETIME 
SET @date = getdate() 

-- 03. inserting test-data 
INSERT INTO dbo.Orders VALUES (1,499.99,'Notebook',@date,'tgr',0) 
INSERT INTO dbo.Orders VALUES (2,650.00,'PC',@date,'tgr',0) 
INSERT INTO dbo.Orders VALUES (3,29.50,'Keyboard',@date,'tgr',0) 

-- 04. adding the duplicate entry 
INSERT INTO dbo.Orders VALUES (2,650.00,'PC',@date,'tgr',0) 

-- 05. viewing the 4 Rows 
SELECT * FROM dbo.Orders 

-- 06. viewing the distinct 3 Rows 
SELECT DISTINCT * FROM dbo.Orders 

/* You don't want to delete the duplicate row, but you want to count 
    the distinct IDs using SUM on the CountMeasure-Column */ 

-- 07. alternativ solution (which may does not fit your requirements) 
/* So your result shoud be the same like this */ 
SELECT COUNT(DISTINCT ID) as DistinctCount 
FROM dbo.Orders 

-- 08. Understanding the solution 
/* To understand the solution we take a look on the main-part 
    We generate for each ID a Row-Number ordered by random 
    Details: https://msdn.microsoft.com/de-de/library/ms186734%28v=sql.120%29.aspx */ 
SELECT * , ROW_NUMBER() OVER (PARTITION BY ID ORDER BY NEWID()) AS RowNumberForEachId 
FROM dbo.Orders 

-- 09. The update statement 
/* We use this part to update our table */ 
UPDATE a 
SET CountMeasure = 1 
FROM (-- Orders incl 
     SELECT * , ROW_NUMBER() OVER (PARTITION BY ID ORDER BY NEWID()) as rowNum 
     FROM dbo.Orders 
) as a 
WHERE rowNum = 1 

-- 10. Viewing the Result 
SELECT * FROM dbo.Orders 

-- 11. Comparing Count(DISTINCT ...) with the SUM(...) alternative 
SELECT COUNT(DISTINCT ID) as countDistinct, SUM(CountMeasure) as sumCountMeasure 
FROM dbo.Orders 

-- 12. Removing the test-table 
DROP TABLE dbo.Orders 
Problemi correlati