How to add varchar and integer in sql server - sql-server

I have to convert int to varchar and need to take care about one more consideration.
For example:
1)My string length is always 10 characters.
(i.e. "0000000001")
Whenever I generated a new id, it has to increment (i.e. "0000000002")
When it reaches the 10th string will be "0000000010", etc...
I have no idea how to implement this.
trying as a first step.
--Declared variable to increment count
declare #CTR INT
--#LIPRequestID is integer this is what i have to add to my
declare #LIPRequestID int
select #LIPRequestID=0
declare #LIPRequestIDstring varchar(max)
select #ctr=0
WHILE #CTR<2
BEGIN
select #ctr=#ctr+1
select #LIPRequestID=#LIPRequestID+1
select #LIPRequestIDstring='00000000'+ CAST(#LIPRequestID AS VARCHAR(10)
print #LIPRequestIDstring
END
but it is throwing the following exception error:
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near '#LIPRequestIDstring'.
can anybody suggest where I am going wrong?

Instead of concatenating the string literal 00000000 with the ID you should use RIGHT:
DECLARE #LIPRequestIDstring varchar(10);
DECLARE #nextLIPRequestID int;
SET #nextLIPRequestID = (SELECT MAX(LIPRequestID) FROM dbo.TableName) + 1;
SET #LIPRequestIDstring = RIGHT('0000000000'+ CONVERT(VARCHAR(10),#nextLIPRequestID),10)

Parenthesis missing in cast function, other things looks fine
select #LIPRequestIDstring='00000000'+ CAST(#LIPRequestID AS VARCHAR(10))--here

Instead of
CAST(#LIPRequestID AS VARCHAR(10)
use
CAST(#LIPRequestID AS VARCHAR(10))

Instead of RIGHT function, we can use REPLACE function. This will help you to implement your two requirements. The length of the ID also can be passed as parameter #IDLength.
DECLARE #CTR INT = 0
DECLARE #LIPRequestID INT = 0
DECLARE #IDLength INT = 8
DECLARE #LIPRequestIDstring VARCHAR(MAX)
WHILE (#CTR < 12)
BEGIN
SELECT #CTR += 1
SELECT #LIPRequestID += 1
PRINT REPLACE(STR(#LIPRequestID, #IDLength), SPACE(1), '0')
END

Yes, Right function really make sence, thanks to sql and stackoverflow.
declare #LIPRequestIDstring varchar(max)
select #LIPRequestID=#LIPRequestID+1
select #LIPRequestIDstring=RIGHT('0000000000'+ CONVERT(VARCHAR(10),#LIPRequestID),10)

Related

generate row number by using variable in mssql

In MYSQL, I could use variable to generate the row number like below:
SET #num=0;
SELECT #num:=#num+1 rownum,id FROM test;
How should I do this in MSSQL? I tried below code:
DECLARE #num int
SET #num=0;
SELECT #num=#num+1 ,id FROM test;
then I got the error message:
A SELECT statement that assigns a value to a variable must not be
combined with data-retrieval operations.
I know there're some built-in functions in mssql to generate the row number, but I'd like to know how to use variables in this case to solve the issue.
Appreciate if someone could help on this. :)
As the error message says, you can't do variable assignment in a select statement that also does data retrieval.
You can assign a variable using a select statement...
declare #myInt int;
select #myvariable = 1; -- works just like "set" in this case
And you can do data retrieval...
select someColumn from MyTable
But not both at the same time.
You can assign a value to a variable when selecting from a table, as long as you don't also select columns that don't get assigned to variables.
declare #myInt int;
select #myInt = myIntColumn from MyTable
If MyTable has a lot of rows in it, it's not clear which row will be used to populate the value of #myInt. SQL is "allowed" to pick any row it wants.
Of course, in your case that doesn't matter, since you're assigning a literal value to the variable. You can do this, where by "can", I mean the syntax won't be rejected:
declare #myInt int = 0;
select #myInt = #myInt + 1
from MyTable
But don't do this. It's an interesting quirk, which I am showing it to you with the good faith assumption that you won't use it. It is not supported and should not be relied upon.
Jeff Moden wrote an article about this where he goes over the dangers.
But don't do it even if you follow his rules.
If you want to create a rownum based on the variable value, you can do that by updating the value in the table like below:
drop table if exists #t
create table #t (id int, rownum int)
insert #t(id) select 100
insert #t(id) select 200
insert #t(id) select 300
insert #t(id) select 400
declare #i int
set #i = 0
update #t set rownum = #i, #i = #i + 1
select * from #t
order by rownum

Remove a value from a comma separated string in sql stored procedure

I have a field that store the comma separated id's of publications. Such as 123456,2345678,123567,2345890 etc. When I pull the data from the database I put it into a json object and the web page loops the values and displays the data. Works great.
What I would like to do is to send the stored proc one of the numbers and the stored proc will remove it from the string and save it back to the table. Such as the end user worked on publication 123567 and now wants to make it completed, so I want to remove it from the string so they don't see it in the future. I have a split function in the database but I don't know how to wire it up to delete or rebuild the string without the publication ID.
I don't have any code to show because I am at a loss to start. I figure I need to pass the entire string and the ID. Split the string and loop each value to rebuild a new string but check if the ID is there and skip it.
Is this the best way to do this?
Thanks for your help
what I've ended up with as the base to work from is:
ALTER FUNCTION dbo.RemovePMID (
#S VARCHAR(MAX)
,#PMID VARCHAR(15)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE #T VARCHAR(50)
DECLARE #W VARCHAR(50)
SET #T = ''
WHILE len(#S) > 0
BEGIN
SET #W = left(#S, charindex(',', #S + ',') - 1)
IF charindex(#W, + #PMID) = 0
SET #T = #T + ',' + #W
SET #S = stuff(#S, 1, charindex(',', #S + ','), '')
END
RETURN substring(#T, 2, len(#T) - 2)
END
GO
No need for loops (please take a peek at Larnu's suggestion for your parse/split function)
That said, consider the following
Example
Declare #S varchar(max) = '123456,2345678,123567,2345890'
Declare #Zap varchar(50)='123456'
Select reverse(stuff(reverse(stuff(replace(','+#S+',',','+#Zap+',',','),1,1,'')),1,1,''))
Returns
2345678,123567,2345890

Return length of NVARCHAR or VARCHAR variable definition

I've declared a variable in a stored procedure:
DECLARE #CurrentChunk NVARCHAR(250)
I would like to use the length of the variable, i.e. 250, later in my sp for computational purposes, and I want to keep my code as dry as possible.
Here's my code (assume #Narrative is a param to the SP):
DECLARE #ChunkSizeCharacters INT,
#NumChunks INT,
#LoopIndex INT,
#CurrentChunk NVARCHAR(250)
SET #ChunkSizeCharacters = 250 -- HERE'S WHERE I WANT THE LENGTH OF #CurrentChunk
SET #NumChunks = CEILING((LEN(#Narrative) * 1.0)/#ChunkSizeCharacters)
SET #LoopIndex = 0;
WHILE (#LoopIndex < #NumChunks)
BEGIN
SET #CurrentChunk = SUBSTRING(#Narrative,
((#LoopIndex * #ChunkSizeCharacters) + 1), #ChunkSizeCharacters)
INSERT INTO [dbo].[Chunks] ([Chunk]) VALUES (#CurrentChunk)
SET #LoopIndex = #LoopIndex + 1
END
Is there a way to ascertain the length of an NVARCHAR or VARCHAR variable definition (please read carefully -- I'm not looking for LEN())?
It seems the MaxLength variant property returns the value you're looking for.
DECLARE #Banana varchar(255) = 'This banana'
SELECT SQL_VARIANT_PROPERTY(#Banana, 'MaxLength')
Returns 255.
If you don't mind overwriting the variable (and if you do, you can assign it to a temp NVARCHAR(MAX)):
SELECT #CurrentChunk = REPLICATE(0, 8000);
SELECT #ChunkSizeCharacters = LEN(#CurrentChunk);
This trick does not and cannot work for NVARCHAR(MAX), but that's presumably no problem, given it's enormous maximum size.
Unfortunately T-SQL has nothing in the way of metadata properties for variables. Even determining the type of an expression is a chore.
Interestingly, the value returned by that SELECT SQL_VARIANT_PROPERTY statement doesn't select into a plain, predefined variable. In the end, I used:
DECLARE #Text VARCHAR(400), #TextLen INT
SELECT #TextLen = CAST(SQL_VARIANT_PROPERTY(ISNULL(#Text, ''), 'MaxLength') AS INT)
Works like a charm for me!

Update field so that parameter in SQL has 16 character length

I am writing a stored procedure that will dummy some credit card data (please note that this is not live!) It is for internal purposes only. This sp runs, but it is only printing out a subset of 10 character (numeric) lengths and not 16. Does anyone have any insight?
Here is my SProc:
DECLARE #RESULT int
DECLARE #cc as varchar(50) = (SELECT ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)))
UPDATE trans
SET trans_CCNUM =(SELECT stuff(#cc,1,LEN(#cc)-4,REPLICATE('x', LEN(#cc)-5)))
where LEN(trans_ccNum) = 16;
PRINT #RESULT
Here are the results
dateCreated trans_CCNUM
2014-09-11 16:55:13.800 xxxx9328
If your example above, #cc is only going to be 9 or 10 characters long...
DECLARE #cc as varchar(50) =
(SELECT ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)))
SELECT #cc,len(#cc)
select stuff(#cc,1,LEN(#cc)-4,REPLICATE('x', LEN(#cc)-5))
That is why you are only seeing 9/10 characters
Try changing the INT to BIGINT and you should be OK

return first view not-numeric chars of string in SQL function fails

I am trying to return the prefix of a VAT number with a SQL function. Because of some changes in these numbers and differences in countries and mistakes in the database, the length of the prefix differs from 0 to 4 characters. So the input of my function is a string, with a prefix of not numeric characters and then some numbers. For example ES012345678, and then i only want to return ES.
I wrote a function for it and it fails, it only returns NULL, even when the input is like the example.
Anyone knows where my mistake is?
here is my SQL code:
ALTER FUNCTION [dbo].[returnPreOfVat]
(
-- Add the parameters for the function here
#VATstring varchar
)
RETURNS varchar
AS
BEGIN
-- Declare the return variable here
DECLARE #Result varchar
DECLARE #char varchar(2)
DECLARE #counter int
SET #counter =1;
SET #char = '';
WHILE (#counter < 5) --check some from the front
BEGIN
SET #char = SUBSTRING(#VATstring, #counter,1); --get next char from front
IF(ISNUMERIC(#char)<>1) -- not numeric
BEGIN
SET #Result = #Result + #char;
END
SET #counter=#counter+1;
END
-- Return the result of the function
RETURN #Result
END
you never initialize the result , Please try:
DECLARE #Result varchar = ''
If recall correctly NULL + str = NULL.
I think a loop is overkill here. I'd combine the LEFT and PATINDEX functions
select LEFT(#VATstring, PATINDEX('%[0-9]%', #VATstring)-1)

Resources