Must declare a scalar variable - sql-server

I was creating a column that will give a me random number but I was getting some errors.
CREATE TABLE tblBookInfo
(
AccessionNumber NVARCHAR(MAX)
RandomNumber NVARCHAR(10);
AccNo NVARCHAR(MAX)
#Upper INT;
#Lower INT
SET #Lower = 1
SET #Upper = 9999
Select #RandomNumber = Round (((#Upper - #Lower -1)* RAND() + #Lower), 0)
SET #AccNo = 'LIBBOOKS' + RandomNumber
SELECT #AccNo
Set AccessionNumber = AccNo
)
ERRORS:
Incorrect syntax near 'RandomNumber'.
Must declare the scalar variable "#Lower".
Must declare the scalar variable "#Upper".
Must declare the scalar variable "#Upper".
Must declare the scalar variable "#AccNo".
Must declare the scalar variable "#AccNo".
tHank you for your help :D

Its not very clear what you are trying to accomplish, but here is my interpretation of your code in the correct T-SQL syntax.
I'm not prepared to guess what you're trying to do below that.
CREATE TABLE tblBookInfo
(
AccessionNumber NVARCHAR(MAX),
RandomNumber NVARCHAR(10),
AccNo NVARCHAR(MAX)
)
DECLARE #Upper INT,
#Lower INT,
#RandomNumber INT
SET #Lower = 1 SET #Upper = 9999
SELECT #RandomNumber = Round (((#Upper - #Lower -1)* RAND() + #Lower), 0)
SELECT #RandomNumber

Related

Generate a string format based on fixed length and numeric units on each increment

I had to write a SP to generate a string with the combination of Country (7 chars) + Province (1 char) + numeric number starts from 01. for eg: JAMAICAK01
where JAMAICA (Country) , K (Province) and 01 is the numeric number that gets incremented by 1 for each transaction.
The issue I have here is the generated string length max is 10, can be lesser than 10 but not >10.
It should be handled in a way with certain rules like
the combination don't exist
When the numeric unit changes from tens to hundreds making the string
length >10, I need to remove the right chars for eg JAMAICAKKK10 to
JAMAICAK10 from the right to make the total max length 10.
In my code below I tried to check if the combination exists and I get the max of it and do the numeric increment from the last one. think it can be done in a better way.
Declare #Province char(2)
Declare #Country varchar(10)
declare #CounProv varchar(10)
Declare #SimilarCounPRov varchar(max) = '';
declare #FinalString nvarchar(12)
declare #s varchar(50)
declare #s1 varchar(50)
declare #s2 varchar(50)
Set #Province = LEFT('KINGSTON', 1)
Set #Country = LEFT('JAMAICA', 7)
Set #CounProv = #Country+#Province
Select #SimilarCounPRov = MAX(field1) from dbo.table where field1
LIKE '%JAMAICAK%'
if #SimilarCounPRov IS NOT NULL
BEGIN
Set #s = (select fn_AlphaOnly('%JAMAICAK99%')) -- returns JAMAICAK
Set #s1 = (select fn_NumericOnly('%JAMAICAK99%')) -- returns 199
set #s2= #s1 +1 -- increment by 1
if len(#FinalString) > 10
----
need help here----`
I'm not sure that I understood all your requirements but if you need to generate strings like : JAMAICAK1,JAMAICAK2,...JAMAICAK10...,JAMAICAK11,...JAMAICA100,JAMAICA101,...JAMAIC1000,JAMAIC1001...
You can try to exploit this piece of code :
Declare #Province char(2)
Declare #Country varchar(10)
Declare #CounProv varchar(10)
Declare #value int
Declare #str_value VARCHAR(100)
Set #Province = LEFT('KINGSTON', 1)
Set #Country = LEFT('JAMAICA', 7)
Set #value = 999999
Set #CounProv = #Country+#Province
Set #str_value = (select CAST(#value AS varchar(100)))
select LEFT(#CounProv,10-LEN(#str_value))+#str_value
Tell me if it helps.

How to use Function in the INSERT INTO Statement [SQL SERVR 2016]

The title says it all. I need to create a table(ID, FirstName, LastName) that will be populated with randomly generated 'words' that have a random length and are created from my 'alphabet'. Each word needs to be randomly generated by the DB. The whole table should have 1,000,000 rows.
Let me fill you in what I have done so far.
Created a VIEW that generates a random number:
CREATE VIEW [dbo].[RANDOM]
AS SELECT RAND() RandomResult
Created a SCALAR FUNCTION that generates a random lengh 'word' from the set of determined 'letters' :
CREATE FUNCTION [dbo].[WordGenerator] (#RandomWord VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS BEGIN
DECLARE #Alphabet VARCHAR(33) = 'abcdefghijklmnoprstuówxyzęąśłżźćń',
#StrLength INT,
#LoopCount INT,
#RandomString VARCHAR(MAX),
#AlphabetLength INT;
SELECT #StrLength = (SELECT RandomResult FROM dbo.Random) * 4 + 7, #LoopCount = 0, #RandomString = '', #AlphabetLength = LEN(#Alphabet);
WHILE (#LoopCount < #StrLength)
BEGIN
SELECT #RandomString = #RandomString + SUBSTRING(#Alphabet, CONVERT(INT, (SELECT RandomResult FROM dbo.Random) * #AlphabetLength), 1)
SET #LoopCount = #LoopCount + 1;
END
RETURN #RandomString;
END
Now I want to use this FUNCTION called 'WordGenerator' in the INSERT INTO Clause however it simply does not work because I am not able to call it.
How can I call my Function that every single time it is supposed to generate a new, random word?
Using SELECT TOP 1 RandomWord FROM dbo.WordGenerator() does not work.
Using SELECT dbo.WordGenerator() does not work.
Using SELECT * FROM dbo.WordGenerator() does not work.
Any ideas?
The issue is that your function expects a parameter that is never used and not passed in. So change it to:
CREATE FUNCTION [dbo].[WordGenerator] ()
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE #Alphabet VARCHAR(33) = 'abcdefghijklmnoprstuówxyzęąśłżźćń',
DECLARE #StrLength INT;
DECLARE #LoopCount INT;
DECLARE #RandomString VARCHAR(MAX);
DECLARE #AlphabetLength INT;
SELECT #StrLength = RandomResult * 4 + 7, #LoopCount = 0, #RandomString = '', #AlphabetLength = LEN(#Alphabet)
FROM dbo.Random;
WHILE #LoopCount < #StrLength
BEGIN
SELECT #RandomString = #RandomString + SUBSTRING(#Alphabet, CONVERT(INT, RandomResult * #AlphabetLength), 1)
FROM dbo.Random;
SET #LoopCount += 1;
END;
RETURN #RandomString;
END;
And then just call it like that: SELECT dbo.WordGenerator(); That's the way you call a scalar function.
SELECT * FROM dbo.WordGenerator(); this way you're calling table valued functions.

Create a random string of digits

I need to create a random string of digits of given length
CREATE FUNCTION UniqConvert
(#calue as varchar(max),
#len as int)
The output should be of the length #len
and should be unique per input #value
I already asked similar question:
Create random string of digits T-SQL
This one has different concept
declare #len int
set #len = 3
DECLARE #Random INT
DECLARE #Upper INT
DECLARE #Lower INT
SET #Lower = power(10,#Len-1) ---- The lowest random number
SET #Upper = power(10,#Len )-1 ---- The highest random number
SELECT #Random = ROUND(((#Upper - #Lower -1) * RAND() + #Lower), 0)
select #Random
Try this
select Cast(Round(Rand()*power(10,#Len),0) as Varchar(30))

update value based on row number?

i'm pretty new to SQL and stored procedures and i'm a bit stuck - so any help would be appreciated
how do i loop through each row and assign it the random value i'm generating?
Here is my Storedproc:
CREATE PROCEDURE StoredProc8
AS
BEGIN
DECLARE #total INT
DECLARE #Count INT = 0
DECLARE #Random INT = 0
SELECT #total = COUNT(CustomerID) FROM Customers
WHILE(#Count<= #total)
BEGIN
SELECT #Random = 2 * RAND()
EXEC ('update Customers set col1= ' + #Random )
SELECT #Count = #Count+1
END
END
If you simple need to assign 0 or 1 randomly - you can use RAND() with random seed:
UPDATE Customers SET COL1 = RAND(CHECKSUM(NEWID()))*2
Demo: http://sqlfiddle.com/#!3/31699/9

SQL Server : create function

I am having a little trouble trying to create a function that I can call to generate a 32 character random ID. I have it working in query editor but it is my understanding that to generate this in multiple lines of results accompanied by existing data from tables I have to create a function and call it. Here is my code:
CREATE FUNCTION [dbo].[Func_Gen_OID] (#NewOID varchar(32))
RETURNS VARCHAR(32) AS
BEGIN
DECLARE #Length int = 32
DECLARE #Output varchar(32)
DECLARE #counter smallint
DECLARE #RandomNumber float
DECLARE #RandomNumberInt tinyint
DECLARE #CurrentCharacter varchar(1)
DECLARE #ValidCharacters varchar(255)
SET #ValidCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
DECLARE #ValidCharactersLength int
SET #ValidCharactersLength = len(#ValidCharacters)
SET #CurrentCharacter = ''
SET #RandomNumber = 0
SET #RandomNumberInt = 0
SET #Output = ''
SET NOCOUNT ON
SET #counter = 1
WHILE #counter < (#Length + 1)
BEGIN
SET #RandomNumber = Rand()
SET #RandomNumberInt = Convert(tinyint, ((#ValidCharactersLength - 1) * #RandomNumber + 1))
SELECT #CurrentCharacter = SUBSTRING(#ValidCharacters, #RandomNumberInt, 1)
SET #counter = #counter + 1
SET #Output = #Output + #CurrentCharacter
RETURN #Output
END
Thanks for any and all help!
instead of RAND() function, use this:
create view ViewRandomNumbers
as
select rand( ) as Number
go
I'll guess you're seeing this error:
Invalid use of a side-effecting operator 'rand' within a function.
You can't use RAND() inside a user-defined function directly (you'd need a view as an intermediary). And in this case, RAND would return the same value for every row of your query anyway as you haven't specified a varying seed (different for each call to the function).
If you want to encapsulate the rest of the logic inside the function, you will need to pass it a randomly-generated value from elsewhere, possibly generated via CHECKSUM() and NEWID().
There are some possibilities mentioned in this SQL Server Central thread
Two issues I see:
You are returning #Output inside your while loop.
You don't need the input parameter as you aren't using it inside the function

Resources