I don't understand what the SQL code is trying to do. Is this some kind of resampling? Please describe in words what you are trying to accomplish, or provide the macro function that you are calling so that we can run it ourselves.
If this is a resampling problem, I would do it all in SAS/IML without bothering with SQL. For example, I'd read in the ID variable, use the UNIQUE function to get the numbers {1,2,3}, and then use RANDGEN to generate random numbers in the range 1:3. I can't tell yet how you are using the X variable.