Skip to main content

Generate Jumbled/Randomized Words Using Custom SQL Function

To fill up my database with test data, I needed to generate dummy text, phone numbers, social security numbers etc. There are data generators out there, but i wanted to write my own, so here it is...

ALTER FUNCTION dbo.fn_WORD_JUMBLER(
      @Text VARCHAR(MAX) = '',
      @DataType INT = 0, -- 0 = random text, 1 = random number
      @DataLenth INT = 10    
)
RETURNS VARCHAR(MAX)
AS
BEGIN
/*
USAGE:

SELECT dbo.fn_word_jumbler('ankeet Is Awesome!', DEFAULT, DEFAULT)
SELECT dbo.fn_word_jumbler('1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ', DEFAULT, DEFAULT)

-- ALPHABETS
SELECT dbo.fn_word_jumbler(DEFAULT, 0, DEFAULT)

-- NUMBERS
SELECT dbo.fn_word_jumbler(DEFAULT, 1, DEFAULT)

=============================================================================

Created By: Ankeet Shah
Purpose: Accepts an input and Returns the same text in reorganized/jumbled/randomized order. Cannot 'de-randomize'.
This function can also be repurposed to be used as random data generator to fill up tables.

*/

            IF @Text = ''
            BEGIN
                  -- set defaults
                  IF @DataType = 0
                        SET @Text = left(replICATE('ABCDEFGHIJKLMNOPQRSTUVWXYZ',100),@DataLenth)
                       
                  IF @DataType = 1
                        SET @Text = left(replICATE('12345678991234567893123456',100),@DataLenth)                 
           
            END           
           
            DECLARE @Jumbled VARCHAR(MAX) = ''
           
            DECLARE @TextLen as INT,
                        @i as INT = 1,
                        @Pick as INT
                       
            DECLARE @Randomize AS TABLE (num INT, id VARCHAR(100))
            SET @TextLen = LEN(@Text)          

            -- Build the table using GetNewID view which compensates for the inability to use newid() in functions.
            WHILE @i <= @TextLen
            BEGIN
                  INSERT INTO @Randomize
                  SELECT @i, NEW_ID
                  FROM dbo.GetNewID
                  SET @i = @i + 1
            END

            SET @i = 1

            -- Run through loop for as many times as is the length of the plain text.
            -- @Randomize table will make sure that characters from the plain text are returned at random.
            WHILE @i <= LEN(@Text)
            BEGIN
                  SELECT @Pick = (SELECT top 1 num FROM @Randomize ORDER BY id)
                 
                  SELECT @Jumbled = @Jumbled + SUBSTRING(@text,@Pick,1)
                 
                  -- remove the number from stack to avoid any duplication
                  DELETE @Randomize WHERE num = @Pick
                  SET @i = @i + 1
            END

            RETURN @Jumbled
 END

MS SQL does not allow the use if NEWID() function within UDFs. An intelligent way out of it is to create a view that does the job for you.

CREATE VIEW dbo.GetNewID
AS
SELECT NEWID() as ID

Keep this function in your back pocket, and you will find it useful at some point!

Comments

Lavanya said…
Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing
Microstrategy Online Training
Microstrategy Online Course

The Popular Ones

Using SQL To Calculate XIRR (Internal Rate of Return)

Thanks to binaryworld.net , I was finally able to get a sql way to calculate XIRR. After 2 long hours of search I found this site and the logic as well as the code works perfectly well! XIRR is a function in excel that calculates Internal Rate of Return based on payments/income over a period of time. Without further ado, here is the code (a slightly modified version from BinaryWorld.net. Happy XIRRing! -- First, CREATE XIRR Table to store values CREATE TABLE XIRRTempData( amt float, dt datetime, guid varchar(128) ) go create function dbo.XIRR( @d datetime, @GUID varchar(128) ) returns decimal(18,10) as begin /* USAGE: select @IRR = dbo.xirr(null, guid) select @IRR IRR, @IRR * 100 'IRR %' Note: Leave the first parameter (date) null if you wish to see the XIRR calculated as of the maximum date in the dataset provided else provide a specific date to see the XIRR calculated as the given date. Created By: Ankeet Shah Created On: 7/16/2008 */ IF @d is null SELECT @d = max(d) from Inc

Alternating Row Background Color For SSRS Matrix (Pivot Table)

I had a tough time to apply alternate row colors to a SSRS Matrix and finally figured out! Without further ado, here it is... Assume you have a matrix with more than 1, lets say 2 row groupings; RG1 and RG2. 1. Right-click on RG2 (innermost row group), and select "Insert Group"; for simplicity call it "RowColorGroup" 2. In the "Group On" section, add some constant value - for example ="" or ="ankeet" etc... you get the idea! 3. Select the newly created group "RowColorGroup" and enter the following in its "Value" property: =iif(RunningValue(Fields!RG1.Value & Fields!RG2.Value,CountDistinct,Nothing) Mod 2, "LightSteelBlue", "White") 4. Select the "BackgroundColor" property of "RowColorGroup" and enter "=Value" 5. Set the width of "RowColorGroup" to 0pt and "CanGrow" to false 6. Select the data cell(s) and set their "BackgroundColor" pro

cannot create a column accessor for OLE DB provider "ibmdasql" for linked server

I have a linked server from Microsoft SQL 2008 to a DB2 server. Today when I tried to run a SELECT statement based on the linked server, I hit this error, "cannot create a column accessor for OLE DB provider "ibmdasql" for linked server". Earlier in the day, we had restarted the SQL Server Service. Running the following script on the 'affected' sql server should fix the issue. USE [master] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROC [dbo].[usp_enum_oledb_providers] AS exec sp_enum_oledb_providers GO sp_procoption 'usp_enum_oledb_providers', 'startup', 1 Restart the sql server service after running above script.