Home > front end >  SQL: Get Random 4 signs long String from value field
SQL: Get Random 4 signs long String from value field

Time:03-02

Is there a way to get random 4 signs out of a Value with SQL?

For Example:

ID TextValue
1 Policestation
2 HarrypotterDVDs
3 Dummyfiredepartment

Out of each Value in textvalue column, I need to pick 4 random signs out of it. Means:

Value:

Policestation => Randomstring: cest

HarrypotterDVDs => Randomstring: Harr

Dummyfiredepartment => Randomstring: tmen

Is there a SQLFunction for that?

CodePudding user response:

If you really want a truly random result picked per row for each execution you could do something like the following. Use a numbers/tally table (here a CTE) and select a random starting position using newid()

with seq as 
  (select top(20) n = Row_Number() over(order by (select null)) from master.dbo.spt_values)
select Substring(textvalue,IsNull(r,1),4)
from t
outer apply (
    select top (1) n
    from seq
    where n <= Len(textvalue)-3
    order by NewId()
)v(r);
  • Related