Search code examples
t-sqltable-functions

Randomizing SQL data with data from table function


I trying to make a sql script that will randomize the city, state, and zip code of a "members" table. I have made a table function that returns a single row with columns "city", "state" and "zip" taken from another database at random (via a view). This ensures that I get a city, state, and zip that actually correlate to each other in the real world.

From there I am trying to do something like this:

update t
set 
t.City = citystate.city,
t.State = citystate.state,
t.PostalCode = citystate.zip

from
(select
 City, 
 State,
 PostalCode from DATABASE.dbo.Member) t,
 DATABASE.dbo.getRandomCityState() citystate

Problem is, this only calls my function once, and puts the same city, state, and zip into every row of the table. Is there some way to call my function once for every row in the table?


Solution

  • Ok so thanks to one of my co-workers, we found a solution. It would seem that since the function didn't take any parameters, SQL Server decided that the result would never change. So we tricked the server into thinking it will be different every time by passing a parameter to the function that was different: the id of each row. Since we were passing a different parameter each time, it called the function for every row.

    update t 
    set 
    t.City = citystate.city,
    t.State = citystate.state,
    t.PostalCode = citystate.zip
    
    from
    (select top 10 
    City, 
     State,
     PostalCode from TrajectoryServicesTest.dbo.Member) t
     cross apply SanitizePhi.dbo.getRandomCityState(t.MemberID) citystate
    

    Kinda hacky, but it worked. Thanks to Joe for the help.