2010-01-07 7 views
4

SQL Server 2000:table mise à jour avec des données aléatoires avec NEWID() ne fonctionne pas

J'ai une table avec des données de test (environ 100 000 lignes), je veux mettre à jour une valeur de colonne d'une autre table avec des données aléatoires d'une autre table. Selon this question, ce que je suis en train:

UPDATE testdata 
SET type = (SELECT TOP 1 id FROM testtypes ORDER BY CHECKSUM(NEWID())) 

-- or even 
UPDATE testdata 
SET type = (SELECT TOP 1 id FROM testtypes ORDER BY NEWID()) 

Cependant, le champ « type » est toujours avec la même valeur pour toutes les lignes; Des idées que fais-je tort?

[EDIT ] Je me attends à cette requête pour retourner une valeur différente pour chaque ligne, mais il ne fonctionne pas:

SELECT testdata.id, (SELECT TOP 1 id FROM testtypes ORDER BY CHECKSUM(NEWID())) type 
FROM testdata 

-- however seeding a rand value works 
SELECT testdata.id, (SELECT TOP 1 id FROM testtypes ORDER BY CHECKSUM(NEWID()) + RAND(testdata.id)) type 
FROM testdata 

Répondre

4

Votre problème est: vous sélectionnez une seule valeur puis en mettant à jour toutes les colonnes avec cette seule valeur.

Afin d'obtenir vraiment une répartition aléatoire va, vous devez faire une étape par étape/approche en boucle - J'ai essayé dans SQL Server 2008, mais je pense que cela devrait fonctionner dans SQL Server 2000 ainsi:

-- declare a temporary TABLE variable in memory 
DECLARE @Temporary TABLE (ID INT) 

-- insert all your ID values (the PK) into that temporary table 
INSERT INTO @Temporary SELECT ID FROM dbo.TestData 

-- check to see we have the values 
SELECT COUNT(*) AS 'Before the loop' FROM @Temporary 

-- pick an ID from the temporary table at random  
DECLARE @WorkID INT 
SELECT TOP 1 @WorkID = ID FROM @Temporary ORDER BY NEWID() 

WHILE @WorkID IS NOT NULL 
BEGIN 
    -- now update exactly one row in your base table with a new random value 
    UPDATE dbo.TestData 
    SET [type] = (SELECT TOP 1 id FROM dbo.TestTypes ORDER BY NEWID()) 
    WHERE ID = @WorkID 

    -- remove that ID from the temporary table - has been updated 
    DELETE FROM @Temporary WHERE ID = @WorkID 

    -- first set @WorkID back to NULL and then pick a new ID from 
    -- the temporary table at random   
    SET @WorkID = NULL 
    SELECT TOP 1 @WorkID = ID FROM @Temporary ORDER BY NEWID() 
END 

-- check to see we have no more IDs left 
SELECT COUNT(*) AS 'After the update loop' FROM @Temporary 
1

vous devez appliquer un par calcul de la ligne dans la sélection des nouveaux ids ..

ce serait faire l'affaire

UPDATE testdata 
SET type = (SELECT TOP 1 id FROM testtypes ORDER BY outerTT*CHECKSUM(NEWID())) 
FROM testtypes outerTT 
Questions connexes