Why does SQL Server conversion to bigint cause an error? - sql

I am trying to convert varchar to bigint:
select convert(bigint, (select(Replace((select value from sometable), ' ', ''))))
Why is it giving error???
Error converting data type varchar to bigint.
thanks in advance
Update
This is part of query I am trying:
select top 1 *
into #tblTemp
from testTable
where Status = 0
order by Sno
declare #mobile varchar(50)
set #mobile = (select(Replace((select mobile from #tblTemp), ' ', '')))
--set #mobile = (select( Replace(' 9428017524', ' ', '')))
select convert(bigint, #mobile)
drop table #tblTemp

Try this
select convert(bigint, CASE WHEN ISNUMERIC(#mobile + 'e0') = 0
THEN 0 ELSE #mobile)
-- add this case statement to return only numeric values,
-- your query will fail for values like '123-415-6789', '(123)415-6789'
Check your mobile numbers data and see if there are any unexpected values in that column, you may have to replace '-' or '(' or ')' etc with ''.
SeLECT * FROM #tblTmp
WHERE ISNUMERIC(Replace(mobile, ' ', '') + 'e0') = 0;

I am not sure what your real string is but for safety you can check ISNUMERIC() before convertion.
DECLARE #mobile varchar(50)
SELECT #mobile = REPLACE(mobile, ' ','') --much simplified version
FROM #tblTemp
IF ISNUMERIC(#mobile)
SELECT CONVERT(bigint, #mobile)
ELSE
SELECT 0
Just by reading your queries, you don't need a temp table here at all. Everything can be done in a single query
SELECT TOP (1) CONVERT(bigint, CASE ISNUMERIC( REPLACE(mobile,' ','') )
WHEN 1 THEN REPLACE(mobile,' ','')
ELSE 0 END )
FROM testTable
WHERE Status = 0
ORDER By Sno

Related

SQL Server 2008 filter conditions in stored procedure script

I would like to have array of characters/strings to omit the condition as below in the stored procedure
if(charindex(#strfileName, ' ')) <=0 and if(charindex(#strfileName, '-') <= 0) and
if(charindex(#strfileName, '-') <= 0) and if(substring(#strfileName, 'report ') <= 0)
What is the best way to do it,through array/list of filtering conditions?
Thanks,
For "array of chars" you may use LIKE:
IF #strfileName NOT LIKE '%[ -!:?]%'
AND #strfileName NOT LIKE '%report%'
and PATINDEX which works similar to CHARINDEX but supports patterns:
DECLARE #strfileName VARCHAR(100) = 'asdf!xxx'
IF PATINDEX('%[ -!:?]%', #strfileName) > 0
PRINT 'bad name'
ELSE
PRINT 'good name'
GO
You should use the CharIndex input arguments in the reverse order
Please check following SQL script which returns the value if it does not contain any of the ban list ( space, '-','.' and 'report')
declare #strfileName nvarchar(max) = N'kodyazcom'
select #strfileName
where
charindex(' ', #strfileName) <= 0 and
charindex('-', #strfileName) <= 0 and
charindex('.', #strfileName) <= 0 and
charindex('report ', #strfileName) <= 0
You can work with table and test using exists(select ...
Declare #tableVerify table (charTest char, strTest varchar(100))
declare #strfileName varchar(100)
set #strfileName = 'file-01.doc'
insert into #tableVerify values (' ', 'report')
insert into #tableVerify values ('-', 'data')
if exists(select * from #tableVerify where not CHARINDEX(charTest, #strfileName) <= 0)
begin
Select '2'
end
else
begin
Select 'e'
end

concat two columns in sql

I have four columns on data gridview and want them to concat in sql and exporting it to txt file but everytime i export this is my result.
My result
0010000 01500 00000 0001600
output required
001000001500000000001600
SQL Query:
string stringSql = " SELECT distinct " +
"REPLACE(RIGHT('00'+CAST(CAST(bat.PCN_Charge* 100.00 AS INT) AS VARCHAR(5)),8) as CLAIMAMT, + RIGHT('0'+CAST(CAST([CFee] * 100 AS INT) AS VARCHAR(5)),5),' ','' )as CFEE," +
"REPLACE(RIGHT('00000'+CAST(CAST([Solictors Fees] AS INT) AS VARCHAR(5)),5), + RIGHT('000'+CAST(CAST(bat.PCN_Charge + [CFee]*100 AS INT) AS VARCHAR(5)),9),' ','') as TotalAMT " +
Judging from the manual:
Method 1: Concatenating two strings
SELECT 'FirstName' + ' ' + 'LastName' AS FullName
Method 2: Concatenating two Numbers
SELECT CAST(1 AS VARCHAR(10)) + ' ' + CAST(2 AS VARCHAR(10))
Method 3: Concatenating values of table columns
SELECT FirstName + ' ' + LastName
FROM AdventureWorks.Person.Contact
In your case, you should do the same, avoiding the space in between.
select first_column+' '+second_c+' '+third_c+' '+forth_c
from table_name
try it
declare #result varchar(500)
set #result = ''
select #result = #result +' '+first_c+' '+second_c+' '+third_c+' '+forth_c
from table_name
declare #a varchar(50)
set #a='0010000 01500 00000 0001600'
select replace(#a,' ','')
SEE DEMO

sybase ISNULL - are the conditions too long?

I am trying to unmangle a very old variable. It was a full name entered all in one field and is found in two separate tables. In most newer places the name is in three logical columns, first, middle, last. In these it is all together and I am trying to strip it out to first initial, last name. I found the following here and modified it:
http://dbaspot.com/sqlserver-programming/365656-find-last-word-string.html
DECLARE #full_name VARCHAR(20)
DECLARE #fullname VARCHAR(20)
SELECT #full_name = REVERSE('John A Test')
SELECT #fullname = REVERSE('Joe Q Public')
SELECT #final = ISNULL(
(right(#full_name,1) + '. ' + (REVERSE(SUBSTRING(#full_name, 1,
CHARINDEX(' ',#full_name) - 1)))),
(right(#fullname,1) + '. ' + (REVERSE(SUBSTRING(#fullname, 1,
CHARINDEX(' ',#fullname) - 1 ))))
)
When I leave full_name there it works fine...returns J. Test. When I null it the default should be
J. Public but instead ends up as .. When I test each line separately they work. I tried COALESCE as well with the same results. Is this too many brackets for ISNULL or ????
You have problem with right(#full_name,1) + '. ', for example:
select null+'.'
gives you ..
Try to change your code using case as below:
DECLARE #full_name VARCHAR(20)
DECLARE #fullname VARCHAR(20)
DECLARE #final VARCHAR(20)
SELECT #full_name = null--REVERSE('John A Test')
SELECT #fullname = REVERSE('Joe Q Public')
SELECT #final = case
when #full_name is not null
then (right(#full_name,1) + '. ' + (REVERSE(SUBSTRING(#full_name, 1,
CHARINDEX(' ',#full_name) - 1))))
else (right(#fullname,1) + '. ' + (REVERSE(SUBSTRING(#fullname, 1,
CHARINDEX(' ',#fullname) - 1 ))))
end
select #final

Using PATINDEX to find varying length patterns in T-SQL

I'm looking to pull floats out of some varchars, using PATINDEX() to spot them. I know in each varchar string, I'm only interested in the first float that exists, but they might have different lengths.
e.g.
'some text 456.09 other text'
'even more text 98273.453 la la la'
I would normally match these with a regex
"[0-9]+[.][0-9]+"
However, I can't find an equivalent for the + operator, which PATINDEX accepts. So they would need to be matched (respectively) with:
'[0-9][0-9][0-9].[0-9][0-9]' and '[0-9][0-9][0-9][0-9][0-9].[0-9][0-9][0-9]'
Is there any way to match both of these example varchars with one single valid PATINDEX pattern?
I blogged about this a while ago.
Extracting numbers with SQL server
Declare #Temp Table(Data VarChar(100))
Insert Into #Temp Values('some text 456.09 other text')
Insert Into #Temp Values('even more text 98273.453 la la la')
Insert Into #Temp Values('There are no numbers in this one')
Select Left(
SubString(Data, PatIndex('%[0-9.-]%', Data), 8000),
PatIndex('%[^0-9.-]%', SubString(Data, PatIndex('%[0-9.-]%', Data), 8000) + 'X')-1)
From #Temp
Wildcards.
SELECT PATINDEX('%[0-9]%[0-9].[0-9]%[0-9]%','some text 456.09 other text')
SELECT PATINDEX('%[0-9]%[0-9].[0-9]%[0-9]%','even more text 98273.453 la la la')
Yes you need to link to the clr to get regex support. But if PATINDEX does not do what you need then regex was designed exactly for that.
http://msdn.microsoft.com/en-us/magazine/cc163473.aspx
Should be checked for robustness (what if you only have an int, for example), but this is just to put you on a track:
if exists (select routine_name from information_schema.routines where routine_name = 'GetFirstFloat')
drop function GetFirstFloat
go
create function GetFirstFloat (#string varchar(max))
returns float
as
begin
declare #float varchar(max)
declare #pos int
select #pos = patindex('%[0-9]%', #string)
select #float = ''
while isnumeric(substring(#string, #pos, 1)) = 1
begin
select #float = #float + substring(#string, #pos, 1)
select #pos = #pos + 1
end
return cast(#float as float)
end
go
select dbo.GetFirstFloat('this is a string containing pi 3.14159216 and another non float 3 followed by a new fload 5.41 and that''s it')
select dbo.GetFirstFloat('this is a string with no float')
select dbo.GetFirstFloat('this is another string with an int 3')
Given that the pattern is going to be varied in length, you're not going to have a rough time getting this to work with PATINDEX. There is another post that I wrote, which I've modified to accomplish what you're trying to do here. Will this work for you?
CREATE TABLE #nums (n INT)
DECLARE #i INT
SET #i = 1
WHILE #i < 8000
BEGIN
INSERT #nums VALUES(#i)
SET #i = #i + 1
END
CREATE TABLE #tmp (
id INT IDENTITY(1,1) not null,
words VARCHAR(MAX) null
)
INSERT INTO #tmp
VALUES('I''m looking for a number, regardless of length, even 23.258 long'),('Maybe even pi which roughly 3.14159265358,'),('or possibly something else that isn''t a number')
UPDATE #tmp SET words = REPLACE(words, ',',' ')
;WITH CTE AS (SELECT ROW_NUMBER() OVER (ORDER BY ID) AS rownum, ID, NULLIF(SUBSTRING(' ' + words + ' ' , n , CHARINDEX(' ' , ' ' + words + ' ' , n) - n) , '') AS word
FROM #nums, #tmp
WHERE ID <= LEN(' ' + words + ' ') AND SUBSTRING(' ' + words + ' ' , n - 1, 1) = ' '
AND CHARINDEX(' ' , ' ' + words + ' ' , n) - n > 0),
ids AS (SELECT ID, MIN(rownum) AS rownum FROM CTE WHERE ISNUMERIC(word) = 1 GROUP BY id)
SELECT CTE.rownum, cte.id, cte.word
FROM CTE, ids WHERE cte.id = ids.id AND cte.rownum = ids.rownum
The explanation and origin of the code is covered in more detail in the origional post
PATINDEX is not powerful enough to do that. You should use regular expressions.
SQL Server has Regular expression support since SQL Server 2005.

Convert SQL Server result set into string

I am getting the result in SQL Server as
SELECT StudentId FROM Student WHERE condition = xyz
I am getting the output like
StudentId
1236
7656
8990
........
The output parameter of the stored procedure is #studentId string and I want the return statement as
1236, 7656, 8990.
How can I convert the output in the single string?
I am returning single column [ie. StudentId]
Test this:
DECLARE #result NVARCHAR(MAX)
SELECT #result = STUFF(
( SELECT ',' + CONVERT(NVARCHAR(20), StudentId)
FROM Student
WHERE condition = abc
FOR xml path('')
)
, 1
, 1
, '')
DECLARE #result varchar(1000)
SELECT #result = ISNULL(#result, '') + StudentId + ',' FROM Student WHERE condition = xyz
select substring(#result, 0, len(#result) - 1) --trim extra "," at end
Use the COALESCE function:
DECLARE #StudentID VARCHAR(1000)
SELECT #StudentID = COALESCE(#StudentID + ',', '') + StudentID
FROM Student
WHERE StudentID IS NOT NULL and Condition='XYZ'
select #StudentID
Both answers are valid, but don't forget to initializate the value of the variable, by default is NULL and with T-SQL:
NULL + "Any text" => NULL
It's a very common mistake, don't forget it!
Also is good idea to use ISNULL function:
SELECT #result = #result + ISNULL(StudentId + ',', '') FROM Student
Use the CONCAT function to avoid conversion errors:
DECLARE #StudentID VARCHAR(1000)
SELECT #StudentID = CONCAT(COALESCE(#StudentID + ',', ''), StudentID)
FROM Student
WHERE StudentID IS NOT NULL and Condition='XYZ'
select #StudentID
The following is a solution for MySQL (not SQL Server), i couldn't easily find a solution to this on stackoverflow for mysql, so i figured maybe this could help someone...
ref: https://forums.mysql.com/read.php?10,285268,285286#msg-285286
original query...
SELECT StudentId FROM Student WHERE condition = xyz
original result set...
StudentId
1236
7656
8990
new query w/ concat...
SELECT group_concat(concat_ws(',', StudentId) separator '; ')
FROM Student
WHERE condition = xyz
concat string result set...
StudentId
1236; 7656; 8990
note: change the 'separator' to whatever you would like
GLHF!
This one works with NULL Values in Table and doesn't require substring operation at the end. COALESCE is not really well working with NULL values in table (if they will be there).
DECLARE #results VARCHAR(1000) = ''
SELECT #results = #results +
ISNULL(CASE WHEN LEN(#results) = 0 THEN '' ELSE ',' END + [StudentId], '')
FROM Student WHERE condition = xyz
select #results
The answer from brad.v is incorrect! It won't give you a concatenated string.
Here's the correct code, almost like brad.v's but with one important change:
DECLARE #results VarChar(1000)
SELECT #results = CASE
WHEN #results IS NULL THEN CONVERT( VarChar(20), [StudentId])
ELSE #results + ', ' + CONVERT( VarChar(20), [StudentId])
END
FROM Student WHERE condition = abc;
See the difference? :) brad.v please fix your answer, I can't do anything to correct it or comment on it 'cause my reputation here is zero. I guess I can remove mine after you fix yours. Thanks!
Use STRING_AGG:
SELECT STRING_AGG(sub.StudentId, ',') FROM
(select * from dbo.Students where Name = 'Test3') as sub
If you want to use e.g ORDER BY:
SELECT STRING_AGG(sub.StudentId, ',') WITHIN GROUP(Order by StudentId) FROM
(select * from dbo.Students where Name = 'Test3') as sub
or a single select statement...
DECLARE #results VarChar(1000)
SELECT #results = CASE
WHEN #results IS NULL THEN CONVERT( VarChar(20), [StudentId])
ELSE ', ' + CONVERT( VarChar(20), [StudentId])
END
FROM Student WHERE condition = abc;
Assign a value when declaring the variable.
DECLARE #result VARCHAR(1000) ='';
SELECT #result = CAST(StudentId AS VARCHAR) + ',' FROM Student WHERE condition = xyz