Left pad varchar to certain length in sql server - sql

I want to left pad int number with 12 digits as 0 and starting with character as 'P'
E.g if number is 345
Then output should be 'P00000000345'
My Code :
Declare #a int
Set #a =8756
Select Right('P00000000000' +Cast(#a As Varchar(11)),12)
DB : SQL SERVER 2008

Try
Declare #a int
Set #a =8756
Select 'P'+Right('00000000000' +Cast(#a As Varchar(11)),11)

Try this
Declare #a int
Set #a =8756
Select 'P' + REPLACE(STR(#a, 11), SPACE(1), '0')
Demo: http://sqlfiddle.com/#!3/d41d8/18547

You're mostly correct, but should apply the P as a separate step:
Declare #a int
Set #a =8756
Select 'P' + Right('000000000000' +Cast(#a As Varchar(11)),12)

Change
Select Right('P00000000000' +Cast(#a As Varchar(11)),12)
to
Select 'P' + Right('00000000000' +Cast(#a As Varchar(11)),11)
SQL Fiddle DEMO

This will left pad the number with zeros. 11 zeros and prepend the 'P', so a total of 12 chars.
declare #a int
set #a = 234
select #a as ORIG, 'P' || str(#a, 11, '0') as CHAR12_STRING

Related

Count numeric chars in string

Using tsql I want to count a numeric chars in string. For example i've got 'kick0my234ass' string and i wanna count how many (4 in that example) numbers are in that string. I can't use regex, just plain tslq.
You COULD do this I suppose:
declare #c varchar(30)
set #c = 'kick0my234ass'
select #c, len(replace(#c,' ','')) - len(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(#c,'0',''),'1',''),'2',''),'3',''),'4',''),'5',''),'6',''),'7',''),'8',''),'9',''),' ',''))
You'll first have to split the character string in its individual characters, evaluate which are numeric, and finally count those that are. This will do the trick:
DECLARE #test TABLE (Example NVARCHAR(255))
INSERT #test
VALUES ('kick0my234ass')
SELECT COUNT(1)
FROM #test AS T
INNER JOIN master..spt_values v
ON v.type = 'P'
AND v.number < len(T.Example)
WHERE SUBSTRING(T.Example, v.number + 1, 1) LIKE '[0-9]'
You could try this solution with regular expressions (if you'd allow them):
it uses recursive CTE, at every recursive step, one digit is removed from given string and the condition is to stop, when there are no digits in string. The rows are also numbered with consecutive ids, so the last id is the amount of removed digits from string.
declare #str varchar(100) = 'kick0my123ass';
with cte as (
select 1 [id], stuff(#str,PATINDEX('%[0-9]%', #str),1,'') [col]
union all
select [id] + 1, stuff([col],PATINDEX('%[0-9]%', [col]),1,'') from cte
where col like '%[0-9]%'
)
--this will give you number of digits in string
select top 1 id from cte order by id desc
Use a WHILE loop to each each character is a numeric or not.
Query
declare #text as varchar(max) = 'kick0my234ass';
declare #len as int;
select #len = len(#text);
if(#len > 0)
begin
declare #i as int = 1;
declare #count as int = 0;
while(#i <= #len)
begin
if(substring(#text, #i, 1) like '[0-9]')
set #count += 1;
set #i += 1;
end
print 'Count of Numerics in ' + #text + ' : ' + cast(#count as varchar(100));
end
else
print 'Empty string';
If simplicity & performance are important I suggest a purely set-based solution. Grab a copy of DigitsOnlyEE which will remove all non-numeric characters. Then use LEN against the output.
DECLARE #string varchar(100) = '123xxx45ff678';
SELECT string = #string, digitsOnly, DigitCount = LEN(digitsOnly)
FROM dbo.DigitsOnlyEE(#string);
Results
string digitsOnly DigitCount
------------------ ----------- ------------
123xxx45ff678 12345678 8
using a Tally Table created by an rCTE:
CREATE TABLE #Sample (S varchar(100));
INSERT INTO #Sample
VALUES ('kick0my234 ass');
GO
WITH Tally AS(
SELECT 1 AS N
UNION ALL
SELECT N + 1
FROM Tally
WHERE N + 1 <= 100)
SELECT S.S, SUM(CASE WHEN SUBSTRING(S,T.N, 1) LIKE '[0-9]' THEN 1 ELSE 0 END) AS Numbers
FROM #Sample S
JOIN Tally T ON LEN(S.S) >= T.N
GROUP BY S.S;
For future reference, also post your owns attempts please. We aren't here (really) to do your work for you.

how to make a left space in a nchar(2) word? [duplicate]

I have the following table A:
id
----
1
2
12
123
1234
I need to left-pad the id values with zero's:
id
----
0001
0002
0012
0123
1234
How can I achieve this?
I believe this may be what your looking for:
SELECT padded_id = REPLACE(STR(id, 4), SPACE(1), '0')
FROM tableA
or
SELECT REPLACE(STR(id, 4), SPACE(1), '0') AS [padded_id]
FROM tableA
I haven't tested the syntax on the 2nd example. I'm not sure if that works 100% - it may require some tweaking - but it conveys the general idea of how to obtain your desired output.
EDIT
To address concerns listed in the comments...
#pkr298 - Yes STR does only work on numbers... The OP's field is an ID... hence number only.
#Desolator - Of course that won't work... the First parameter is 6 characters long. You can do something like:
SELECT REPLACE(STR(id,
(SELECT LEN(MAX(id)) + 4 FROM tableA)), SPACE(1), '0') AS [padded_id] FROM tableA
this should theoretically move the goal posts... as the number gets bigger it should ALWAYS work.... regardless if its 1 or 123456789...
So if your max value is 123456... you would see 0000123456 and if your min value is 1 you would see 0000000001
SQL Server now supports the FORMAT function starting from version 2012, so:
SELECT FORMAT(id, '0000') FROM TableA
will do the trick.
If your id or column is in a varchar and represents a number you convert first:
SELECT FORMAT(CONVERT(INT,id), '0000') FROM TableA
Old post, but maybe this helps someone out:
To complete until it ends up with 4 non-blank characters:
SELECT RIGHT ('0000'+COLUMNNAME, 4) FROM TABLENAME;
To complete until 10:
SELECT RIGHT ('0000000000'+COLUMNNAME, 10) FROM TABLENAME;
In case the column is numeric, convert it to varchar first with such code:
Select RIGHT('0000'+Convert(nvarchar(20), COLUMNNAME), 4)
From TABLENAME
And to complete until 10 with a numeric field:
SELECT RIGHT ('0000000000'+Convert(nvarchar(20), COLUMNNAME), 10) FROM TABLENAME;
declare #T table(id int)
insert into #T values
(1),
(2),
(12),
(123),
(1234)
select right('0000'+convert(varchar(4), id), 4)
from #T
Result
----
0001
0002
0012
0123
1234
Try this:
SELECT RIGHT(REPLICATE('0',4)+CAST(Id AS VARCHAR(4)),4) FROM [Table A]
-- Please look into these.
select FORMAT(1, 'd4');
select FORMAT(2, 'd4');
select FORMAT(12, 'd4');
select FORMAT(123, 'd4');
select FORMAT(1234, 'd4');
-- I hope these would help you
This works for strings, integers and numeric:
SELECT CONCAT(REPLICATE('0', 4 - LEN(id)), id)
Where 4 is desired length. Works for numbers with more than 4 digits, returns empty string on NULL value.
If someone is still interested, I found this article on DATABASE.GUIDE:
Left Padding in SQL Server – 3 LPAD() Equivalents
In short, there are 3 methods mentioned in that article.
Let's say your id=12 and you need it to display as 0012.
Method 1 – Use the RIGHT() Function
The first method uses the RIGHT() function to return only the rightmost part of the string, after adding some leading zeros.
SELECT RIGHT('00' + '12', 4);
Result:
0012
Method 2 – Use a Combination of RIGHT() and REPLICATE()
This method is almost the same as the previous method, with the only difference being that I simply replace the three zeros with the REPLICATE() function:
SELECT RIGHT(REPLICATE('0', 2) + '12', 4);
Result:
0012
Method 3 – Use a Combination of REPLACE() and STR()
This method comes from a completely different angle to the previous methods:
SELECT REPLACE(STR('12', 4),' ','0');
Result:
0012
Check out the article, there is more in depth analysis with examples.
This is what I normally use when I need to pad a value.
SET #PaddedValue = REPLICATE('0', #Length - LEN(#OrigValue)) + CAST(#OrigValue as VARCHAR)
I created a function to do this, where you can specify the desired output character length:
CREATE FUNCTION [dbo].[udfLeadingZero]
(
#String VARCHAR(MAX)
, #Len INT
)
RETURNS VARCHAR(MAX)
BEGIN
SET #String = RIGHT(REPLICATE('0',#Len)+#String,#Len)
RETURN #String
END
GO
Example results
I needed this in a function on SQL server and adjusted Patrick's answer a bit.
declare #dossierId int = 123
declare #padded_id varchar(7)
set #padded_id = REPLACE(
SPACE(7 - LEN(#dossierId)) + convert(varchar(7), #dossierId),
SPACE(1),
'0')
SELECT #dossierId as '#dossierId'
,SPACE(LEN(#dossierId)) + convert(varchar(7)
,#dossierId) as withSpaces
,#padded_id as '#padded_id'
Create Function :
Create FUNCTION [dbo].[PadLeft]
(
#Text NVARCHAR(MAX) ,
#Replace NVARCHAR(MAX) ,
#Len INT
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE #var NVARCHAR(MAX)
SELECT #var = ISNULL(LTRIM(RTRIM(#Text)) , '')
RETURN RIGHT(REPLICATE(#Replace,#Len)+ #var, #Len)
END
Example:
Select dbo.PadLeft('123456','0',8)
I created a function:
CREATE FUNCTION [dbo].[fnPadLeft](#int int, #Length tinyint)
RETURNS varchar(255)
AS
BEGIN
DECLARE #strInt varchar(255)
SET #strInt = CAST(#int as varchar(255))
RETURN (REPLICATE('0', (#Length - LEN(#strInt))) + #strInt);
END;
Use: select dbo.fnPadLeft(123, 10)
Returns: 0000000123
Something fairly ODBC compliant if needed might be the following:
select ifnull(repeat('0', 5 - (floor(log10(FIELD_NAME)) + 1)), '')
+ cast (FIELD as varchar(10))
from TABLE_NAME
This bases on the fact that the amount of digits for a base-10 number can be found by the integral component of its log. From this we can subtract it from the desired padding width. Repeat will return null for values under 1 so we need ifnull.
My solution is not efficient but helped me in situation where the values (bank cheque numbers and wire transfer ref no.) were stored as varchar where some entries had alpha numeric values with them and I had to pad if length is smaller than 6 chars.
Thought to share if someone comes across same situation
declare #minlen int = 6
declare #str varchar(20)
set #str = '123'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 000123
set #str = '1234'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 001234
set #str = '123456'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 123456
set #str = '123456789'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 123456789
set #str = '123456789'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 123456789
set #str = 'NEFT 123456789'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: NEFT 123456789
A simple example would be
DECLARE #number INTEGER
DECLARE #length INTEGER
DECLARE #char NVARCHAR(10)
SET #number = 1
SET #length = 5
SET #char = '0'
SELECT FORMAT(#number, replicate(#char, #length))
More efficient way is :
Select id, LEN(id)
From TableA
Order by 2,1
The result :
id
----
1
2
12
123
1234

What T-SQL statement can add leading zeros to a column of numbers? [duplicate]

I have the following table A:
id
----
1
2
12
123
1234
I need to left-pad the id values with zero's:
id
----
0001
0002
0012
0123
1234
How can I achieve this?
I believe this may be what your looking for:
SELECT padded_id = REPLACE(STR(id, 4), SPACE(1), '0')
FROM tableA
or
SELECT REPLACE(STR(id, 4), SPACE(1), '0') AS [padded_id]
FROM tableA
I haven't tested the syntax on the 2nd example. I'm not sure if that works 100% - it may require some tweaking - but it conveys the general idea of how to obtain your desired output.
EDIT
To address concerns listed in the comments...
#pkr298 - Yes STR does only work on numbers... The OP's field is an ID... hence number only.
#Desolator - Of course that won't work... the First parameter is 6 characters long. You can do something like:
SELECT REPLACE(STR(id,
(SELECT LEN(MAX(id)) + 4 FROM tableA)), SPACE(1), '0') AS [padded_id] FROM tableA
this should theoretically move the goal posts... as the number gets bigger it should ALWAYS work.... regardless if its 1 or 123456789...
So if your max value is 123456... you would see 0000123456 and if your min value is 1 you would see 0000000001
SQL Server now supports the FORMAT function starting from version 2012, so:
SELECT FORMAT(id, '0000') FROM TableA
will do the trick.
If your id or column is in a varchar and represents a number you convert first:
SELECT FORMAT(CONVERT(INT,id), '0000') FROM TableA
Old post, but maybe this helps someone out:
To complete until it ends up with 4 non-blank characters:
SELECT RIGHT ('0000'+COLUMNNAME, 4) FROM TABLENAME;
To complete until 10:
SELECT RIGHT ('0000000000'+COLUMNNAME, 10) FROM TABLENAME;
In case the column is numeric, convert it to varchar first with such code:
Select RIGHT('0000'+Convert(nvarchar(20), COLUMNNAME), 4)
From TABLENAME
And to complete until 10 with a numeric field:
SELECT RIGHT ('0000000000'+Convert(nvarchar(20), COLUMNNAME), 10) FROM TABLENAME;
declare #T table(id int)
insert into #T values
(1),
(2),
(12),
(123),
(1234)
select right('0000'+convert(varchar(4), id), 4)
from #T
Result
----
0001
0002
0012
0123
1234
Try this:
SELECT RIGHT(REPLICATE('0',4)+CAST(Id AS VARCHAR(4)),4) FROM [Table A]
-- Please look into these.
select FORMAT(1, 'd4');
select FORMAT(2, 'd4');
select FORMAT(12, 'd4');
select FORMAT(123, 'd4');
select FORMAT(1234, 'd4');
-- I hope these would help you
This works for strings, integers and numeric:
SELECT CONCAT(REPLICATE('0', 4 - LEN(id)), id)
Where 4 is desired length. Works for numbers with more than 4 digits, returns empty string on NULL value.
If someone is still interested, I found this article on DATABASE.GUIDE:
Left Padding in SQL Server – 3 LPAD() Equivalents
In short, there are 3 methods mentioned in that article.
Let's say your id=12 and you need it to display as 0012.
Method 1 – Use the RIGHT() Function
The first method uses the RIGHT() function to return only the rightmost part of the string, after adding some leading zeros.
SELECT RIGHT('00' + '12', 4);
Result:
0012
Method 2 – Use a Combination of RIGHT() and REPLICATE()
This method is almost the same as the previous method, with the only difference being that I simply replace the three zeros with the REPLICATE() function:
SELECT RIGHT(REPLICATE('0', 2) + '12', 4);
Result:
0012
Method 3 – Use a Combination of REPLACE() and STR()
This method comes from a completely different angle to the previous methods:
SELECT REPLACE(STR('12', 4),' ','0');
Result:
0012
Check out the article, there is more in depth analysis with examples.
This is what I normally use when I need to pad a value.
SET #PaddedValue = REPLICATE('0', #Length - LEN(#OrigValue)) + CAST(#OrigValue as VARCHAR)
I created a function to do this, where you can specify the desired output character length:
CREATE FUNCTION [dbo].[udfLeadingZero]
(
#String VARCHAR(MAX)
, #Len INT
)
RETURNS VARCHAR(MAX)
BEGIN
SET #String = RIGHT(REPLICATE('0',#Len)+#String,#Len)
RETURN #String
END
GO
Example results
I needed this in a function on SQL server and adjusted Patrick's answer a bit.
declare #dossierId int = 123
declare #padded_id varchar(7)
set #padded_id = REPLACE(
SPACE(7 - LEN(#dossierId)) + convert(varchar(7), #dossierId),
SPACE(1),
'0')
SELECT #dossierId as '#dossierId'
,SPACE(LEN(#dossierId)) + convert(varchar(7)
,#dossierId) as withSpaces
,#padded_id as '#padded_id'
Create Function :
Create FUNCTION [dbo].[PadLeft]
(
#Text NVARCHAR(MAX) ,
#Replace NVARCHAR(MAX) ,
#Len INT
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE #var NVARCHAR(MAX)
SELECT #var = ISNULL(LTRIM(RTRIM(#Text)) , '')
RETURN RIGHT(REPLICATE(#Replace,#Len)+ #var, #Len)
END
Example:
Select dbo.PadLeft('123456','0',8)
I created a function:
CREATE FUNCTION [dbo].[fnPadLeft](#int int, #Length tinyint)
RETURNS varchar(255)
AS
BEGIN
DECLARE #strInt varchar(255)
SET #strInt = CAST(#int as varchar(255))
RETURN (REPLICATE('0', (#Length - LEN(#strInt))) + #strInt);
END;
Use: select dbo.fnPadLeft(123, 10)
Returns: 0000000123
Something fairly ODBC compliant if needed might be the following:
select ifnull(repeat('0', 5 - (floor(log10(FIELD_NAME)) + 1)), '')
+ cast (FIELD as varchar(10))
from TABLE_NAME
This bases on the fact that the amount of digits for a base-10 number can be found by the integral component of its log. From this we can subtract it from the desired padding width. Repeat will return null for values under 1 so we need ifnull.
My solution is not efficient but helped me in situation where the values (bank cheque numbers and wire transfer ref no.) were stored as varchar where some entries had alpha numeric values with them and I had to pad if length is smaller than 6 chars.
Thought to share if someone comes across same situation
declare #minlen int = 6
declare #str varchar(20)
set #str = '123'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 000123
set #str = '1234'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 001234
set #str = '123456'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 123456
set #str = '123456789'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 123456789
set #str = '123456789'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 123456789
set #str = 'NEFT 123456789'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: NEFT 123456789
A simple example would be
DECLARE #number INTEGER
DECLARE #length INTEGER
DECLARE #char NVARCHAR(10)
SET #number = 1
SET #length = 5
SET #char = '0'
SELECT FORMAT(#number, replicate(#char, #length))
More efficient way is :
Select id, LEN(id)
From TableA
Order by 2,1
The result :
id
----
1
2
12
123
1234

Convert Comma Delimited String to bigint in SQL Server

I have a varchar string of delimited numbers separated by commas that I want to use in my SQL script but I need to compare with a bigint field in the database. Need to know to convert it:
DECLARE #RegionID varchar(200) = null
SET #RegionID = '853,834,16,467,841,460,495,44,859,457,437,836,864,434,86,838,458,472,832,433,142,154,159,839,831,469,442,275,840,299,446,220,300,225,227,447,301,450,230,837,441,835,302,477,855,411,395,279,303'
SELECT a.ClassAdID, -- 1
a.AdURL, -- 2
a.AdTitle, -- 3
a.ClassAdCatID, -- 4
b.ClassAdCat, -- 5
a.Img1, -- 6
a.AdText, -- 7
a.MemberID, -- 9
a.Viewed, -- 10
c.Domain, -- 11
a.CreateDate -- 12
FROM ClassAd a
INNER JOIN ClassAdCat b ON b.ClassAdCAtID = a.ClassAdCAtID
INNER JOIN Region c ON c.RegionID = a.RegionID
AND a.PostType = 'CPN'
AND DATEDIFF(d, GETDATE(), ExpirationDate) >= 0
AND a.RegionID IN (#RegionID)
AND Viewable = 'Y'
This fails with the following error:
Error converting data type varchar to bigint.
RegionID In the database is a bigint field.. need to convert the varchar to bigint.. any ideas..?
Many thanks in advance,
neojakey
create this function:
CREATE function [dbo].[f_split]
(
#param nvarchar(max),
#delimiter char(1)
)
returns #t table (val nvarchar(max), seq int)
as
begin
set #param += #delimiter
;with a as
(
select cast(1 as bigint) f, charindex(#delimiter, #param) t, 1 seq
union all
select t + 1, charindex(#delimiter, #param, t + 1), seq + 1
from a
where charindex(#delimiter, #param, t + 1) > 0
)
insert #t
select substring(#param, f, t - f), seq from a
option (maxrecursion 0)
return
end
change this part:
AND a.RegionID IN (select val from dbo.f_split(#regionID, ','))
Change this for better overall performance:
AND DATEDIFF(d, 0, GETDATE()) <= ExpirationDate
Your query does not know that those are separate values, you can use dynamic sql for this:
DECLARE #RegionID varchar(200) = null
SET #RegionID = '853,834,16,467,841,460,495,44,859,457,437,836,864,434,86,838,458,472,832,433,142,154,159,839,831,469,442,275,840,299,446,220,300,225,227,447,301,450,230,837,441,835,302,477,855,411,395,279,303'
declare #sql nvarchar(Max)
set #sql = 'SELECT a.ClassAdID, -- 1
a.AdURL, -- 2
a.AdTitle, -- 3
a.ClassAdCatID, -- 4
b.ClassAdCat, -- 5
a.Img1, -- 6
a.AdText, -- 7
a.MemberID, -- 9
a.Viewed, -- 10
c.Domain, -- 11
a.CreateDate -- 12
FROM ClassAd a
INNER JOIN ClassAdCat b ON b.ClassAdCAtID = a.ClassAdCAtID
INNER JOIN Region c ON c.RegionID = a.RegionID
AND a.PostType = ''CPN''
AND DATEDIFF(d, GETDATE(), ExpirationDate) >= 0
AND a.RegionID IN ('+#RegionID+')
AND Viewable = ''Y'''
exec sp_executesql #sql
I use this apporach sometimes and find it very good.
It transfors your comma-separated string into an AUX table (called #ARRAY) and then query the main table based on the AUX table:
declare #RegionID varchar(50)
SET #RegionID = '853,834,16,467,841,460,495,44,859,457,437,836,864,434,86,838,458,472,832,433,142,154,159,839,831,469,442,275,840,299,446,220,300,225,227,447,301,450,230,837,441,835,302,477,855,411,395,279,303'
declare #S varchar(20)
if LEN(#RegionID) > 0 SET #RegionID = #RegionID + ','
CREATE TABLE #ARRAY(region_ID VARCHAR(20))
WHILE LEN(#RegionID) > 0 BEGIN
SELECT #S = LTRIM(SUBSTRING(#RegionID, 1, CHARINDEX(',', #RegionID) - 1))
INSERT INTO #ARRAY (region_ID) VALUES (#S)
SELECT #RegionID = SUBSTRING(#RegionID, CHARINDEX(',', #RegionID) + 1, LEN(#RegionID))
END
select * from your_table
where regionID IN (select region_ID from #ARRAY)
It avoids you from ahving to concatenate the query string and then use EXEC to execute it, which I dont think it is a very good approach.
if you need to run the code twice you will need to drop the temp table
I think the answer should be kept simple.
Try using CHARINDEX like this:
DECLARE #RegionID VARCHAR(200) = NULL
SET #RegionID =
'853,834,16,467,841,460,495,44,859,457,437,836,864,434,86,838,458,472,832,433,142,154,159,839,831,469,442,275,840,299,446,220,300,225,227,447,301,450,230,837,441,835,302,477,855,411,395,279,303'
SELECT 1
WHERE Charindex('834', #RegionID) > 0
SELECT 1
WHERE Charindex('999', #RegionID) > 0
When CHARINDEX finds the value in the large string variable, it will return it's position, otherwise it return 0.
Use this as a search tool.
The easiest way to change this query is to replace the IN function with a string function. Here is what I consider the safest approach using LIKE (which is portable among databases):
AND ','+#RegionID+',' like '%,'+cast(a.RegionID as varchar(255))+',%'
Or CHARINDEX:
AND charindex(','+cast(a.RegionID as varchar(255))+',', ','+#RegionID+',') > 0
However, if you are explicitly putting the list in your code, why not use a temporary table?
declare #RegionIds table (RegionId int);
insert into #RegionIds
select 853 union all
select 834 union all
. . .
select 303
Then you can use the table in the IN clause:
AND a.RegionId in (select RegionId from #RegionIds)
or in a JOIN clause.
I like Diego's answer some, but I think my modification is a little better because you are declaring a table variable and not creating an actual table. I know the "in" statement can be a little slow, so I did an inner join since I needed some info from the Company table anyway.
declare #companyIdList varchar(1000)
set #companyIdList = '1,2,3'
if LEN(#companyIdList) > 0 SET #companyIdList = #companyIdList + ','
declare #CompanyIds TABLE (CompanyId bigint)
declare #S varchar(20)
WHILE LEN(#companyIdList) > 0 BEGIN
SELECT #S = LTRIM(SUBSTRING(#companyIdList, 1, CHARINDEX(',', #companyIdList) - 1))
INSERT INTO #CompanyIds (CompanyId) VALUES (#S)
SELECT #companyIdList = SUBSTRING(#companyIdList, CHARINDEX(',', #companyIdList) + 1, LEN(#companyIdList))
END
select d.Id, d.Name, c.Id, c.Name
from [Division] d
inner join [Company] c on d.CompanyId = c.Id
inner join #CompanyIds cids on c.Id = cids.CompanyId

why sql convert a number to '*' charachter

i run this query in SQL Server 2008
declare #a varchar(1)
select #a = 22
select #a
it's return this
*
why this query make this result ?
You are converting a 2 character number into a 1 character field.
It won't fit.
SQL is indicating the data is missing. Otherwise, it would display just a 2 and you wouldn't know if this was the full value or not.
insufficient space was detected -
declare #a varchar(2)
select #a = 242
select #a
this will also do that
Use following code:
declare #a varchar(2)
select #a = 22
select #a