I’ve the following SQL statement to pick a random value which doesn’t exist in a DB table:
select CONVERT(INT, 1 + 999999999 * rand()) as NEW_DVAL
WHERE NEW_DVAL NOT IN (SELECT FIELD_DVAL FROM dbo.MASTER_REF)
It completed with errors: Invalid column name.
I find no way to get it done, please kindly help.
Thanks!
William
Unfortunately, you can’t use an alias (“as NEW_DVAL”) in a where clause. You can do this:
However, that I suspect that your query won’t do what you want anyway. The “select convert(…)” bit will give you ONE row, which the “where” bit will either filter out, or not.
If the randomly selected new dval already exists, the query will return no rows – it won’t automatically loop until it finds an unused one.
Take a look at K Ivanov’s answer for a solution to this.