I am trying to create a SQL script that fills a table with a new primary key.
what i currently have from internet searches is the following
DECLARE @IntVariable int;
DECLARE @Stringkey varchar(2);
DECLARE @SQLString nvarchar(500);
DECLARE @Intupdater nvarchar(500);
SET @IntVariable = 00000001;
SET @Stringkey = 'CD';
SET @SQLString = N'UPDATE Tri_Damen_Live.trimergo.calendar_details SET details_key = @Stringkey + @IntVariable';
SET @Intupdater = N'@IntVariable = @IntVariable+1'
EXECUTE sp_executesql @SQLString , N'@IntVariable INT' , N'@Stringkey VARCHAR(2)', @IntVariable, @Stringkey;
The errors I get with this are
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '='.
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "@Stringkey".
I have a few questions about my problem and hope someone might be able to help me
First question : it seems my int
increaser is wrong. is there a way to make a update variable statement for the int?
Second : I declared the int as 00000001. But I doubt it stays like this. The reason I do this is because the key needs to be a set 10 characters long in total (example 'CD00000001' etc) does this work like this or is there another way?
Third question : as the topic stated. The 'Must declare the scalar variable "@Stringkey".' error. I have removed the stringkey part but then it says the same error about the Int
variable. I declared them at the top and set them as well. What am I missing?
Side information :
this function will be used for multiple databases with varying table sizes. So I need this kind of function to account that it does not have a set amount of update statements.
The primary key that is created here must be a string (Varchar(10)
) that is ALWAYS 10 characters long. Seems like a silly requirement but it has been chosen to use this system.
I am using Microsoft SQL Server 2012 to run this in.
SET @IntVariable = 00000001;
the value of that variable (of type int) is just1
. Leading zeroes have no meaning for a number. – Hans KestingCHAR(10)
and save yourself 2 bytes (per entry) of unnecessary overhead! That's quite important if your primary key is also the clustering key – marc_s