How to check numeric value in sql? - sql-server

Here is my code. I want only numeric character. If it is other than numeric, should not print.
Here #msg is substring of one of string,which dynamically created.So I can not change type of #msg to int.It can be ',,3' or '4,,,',etc.Sometime #msg contain comma,so I want to check for numeric.Isnumeric() consider comma as numeric.I gives 1 as result.How to handle it?
Declare #msg varchar(5)
set #msg = ',5'
if(isnumeric(#msg) = 1)
begin
print 'Numeric'
-- logic
end

IsNumeric certainly has idiosyncrasies. They are well discussed in the community. See here for some discussion seesimple talk.
What you actually need to do is not quite clear between the questions and comments, but you might get by with something as simple as checking to make sure there isn't a comma either:
DECLARE #msg VARCHAR(5)
SET #msg = ',5'
IF IsNumeric(#msg) = 1 AND CharIndex(',',#msg,1) = 0
BEGIN
PRINT 'Numeric'
-- logic
END
For more ideas on how to do a better IsNumeric see similar questions like efficient-isnumeric-replacements-on-sql-server.

I think you just want to validate that your variable contains only numeric value or not. use the query..
declare #ClientID varchar(100)
declare #filename varchar(1000)
set #filename = '3081PDShivamCSS_MDaily.Dat'
set #ClientID = substring('3081PDShivamCSS_MDaily.Dat', 1,4)
If #ClientID Not LIKE '%[^0-9]%'
Print Numeric

Related

How to separate Arabic and English text in a string value?

I am getting data from a source like this:
Air Passage - First Time Joining تذاكر سفر حضور لأول مره
I need to split this kind of data into two columns, English text should go into one column and Arabic text should go into the other column.
Can any one help me with this please?
One easy solution would be (if possible) format the data to something like this:
Air Passage - First Time Joining | تذاكر سفر حضور لأول مره
And then you just need to do an split by "|".
REGEX
(?P<en>[a-zA-Z-\s]+) (?P<ar>[\w\s]+)
Kiki is nice tool to test for multiple cases (You may need to add more characters to the ranges)
I did remove ^ and $ to be more general case.
USE [HRData]
GO
/* Object: UserDefinedFunction [dbo].[StripVenNameAR] Script Date: 1/14/2014 8:50:31 AM */
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE FUNCTION [dbo].[StripVenNameAR] (#InString as NVarChar(4000))
RETURNS smallint AS
BEGIN
Declare #ReturnVal as smallint
Declare #OutString as NVarchar(4000)
Declare #Pos as smallint
Declare #CurChar as NVarChar(1)
SET #ReturnVal = 0
IF LEN(#InString) = 0
SET #ReturnVal = 0
ELSE
BEGIN
Set #Pos = 1
SET #OutString = ' '
WHILE (#Pos <= Len(#InString))
BEGIN
Set #CurChar = SUBSTRING(#InString, #Pos, 1)
if unicode(#CurChar) between 1536 and 1791
SET #ReturnVal = #Pos
Set #Pos = #Pos + 1
if #ReturnVal>=1
Break
else
continue
END
end
RETURN #ReturnVal
end
GO

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)

Issue converting varchar to INT in sql server

I have seen this question all over stackoverflow, but it seems that there are a wide number of solutions tailored to the situation. It seems I have a unique situation as far as I can tell. I am running this sql statement
use IST_CA_2_Batch_Conversion
GO
--T-SQL script to populate the Match type column
declare #MatchType varchar(16),
#PK varchar(500),
#CAReturnCode VARCHAR(255),
#CAErrorCodes VARCHAR(255)
declare cursor1 cursor fast_forward for
select
["Ref#"],
["Return Code"],
["Error Codes"]
from CACodes2MatchType
open cursor1
fetch next from cursor1 into #PK,#CAReturnCode,#CAErrorCodes
while ##fetch_status = 0
begin
set #MatchType = dbo.GetMatchType(#CAReturnCode,#CAErrorCodes)
update CACodes2MatchType
set [Match Type] = #MatchType
where ["Ref#"] = #PK
fetch next from cursor1 into #PK,#CAReturnCode,#CAErrorCodes
end
close cursor1
deallocate cursor1
It will fail at
set #MatchType = dbo.GetMatchType(#CAReturnCode,#CAErrorCodes)
Here is the beginning code for the GetMatchType function:
-- Batch submitted through debugger:
SQLQuery14.sql|6|0|C:\Users\b01642a\AppData\Local\Temp\~vs1C8E.sql
CREATE FUNCTION [dbo].[GetMatchType](#CAReturnCode VARCHAR(255), #CAErrorCodes
VARCHAR(255))
RETURNS VARCHAR(16)
BEGIN
DECLARE #MatchType VARCHAR(16);
DECLARE #errorCodes TABLE(Pos INT, Code CHAR(2));
DECLARE #country INT; -- 1 is US, 2 is Canada
DECLARE #numMinorChanges INT;
DECLARE #numMajorChanges INT;
DECLARE #numSingleCodes INT;
DECLARE #returnCode INT;
DECLARE #verified VARCHAR(16);
DECLARE #goodFull VARCHAR(16);
DECLARE #tentativeFull VARCHAR(16);
DECLARE #poorFull VARCHAR(16);
DECLARE #multipleMatch VARCHAR(16);
DECLARE #unmatched VARCHAR(16);
SET #verified = 'Verified';
SET #goodFull = 'Good Full';
SET #tentativeFull = 'Tentative Full';
SET #poorFull = 'Poor Full';
SET #multipleMatch = 'Multiple Match';
SET #unmatched = 'Unmatched';
SET #returnCode = CAST(#CAReturnCode AS INT);
I will get the error: Msg 245, Level 16, State 1, Line 21
Conversion failed when converting the varchar value '"1"' to data type int.
This error occurs at the last line of the code segment I have shown:
SET #returnCode = CAST(#CAReturnCode AS INT);
This is code that was written by a colleague and supposedly had worked for him. I have had to troubleshoot some errors but I cannot debug this one. I understand alot of people will create a dbo.split function? I don't know if this option will help me in this scenario. I have tried setting #returnCode to a varchar and getting rid of the CAST on #CAReturnCode. As a result, the debugger will make it past that line but raises issues with the rest of the code. I am assuming there is an issue with how I am casting #CAReturnCode? Any help would be much appreciated.
The problem is that #CAReturnCode contains non-numeric characters.
-- Msg 245, Level 16, State 1, Line 21 Conversion failed when converting the varchar value '"1"' to data type int.
See, the outer single quotes are the error message's formatting, but the inner double quotes are in the #CAReturnCode value. So the solution here is to ensure that the variable contains only numeric characters prior to converting. If double quotes are the only possibility, you can do a quick and dirty fix like this:
set #returnCode = cast(replace(#CAReturnCode, '"', '') as int)
If there are more possibilities, you could do multiple REPLACE calls, or you could build a better character-trimming function that will remove all the characters you specify at once yourself.

Cursor not looping correctly

I have a cursor that I want to loop through a staging table, and merge each record into another table.
I cant get this cursor just to loop through the records and return a count.
DECLARE #curCatalogID int
DECLARE #curNomenclature varchar(200)
DECLARE #curMainCategory varchar(200)
DECLARE #curSubCategory varchar(200)
DECLARE #curManufacturer varchar(200)
DECLARE #curModelNo varchar(200)
DECLARE #curPrice varchar(200)
DECLARE #curProductDesc varchar(2000)
DECLARE #curImage varchar(200)
DECLARE #curPDFName varchar(200)
DECLARE #curInventory varchar(200)
DECLARE #curBatchID int
DECLARE #curAuditID int
DECLARE #nCnt int
SET #nCnt = 0
DECLARE import_loop CURSOR FOR
SELECT * FROM tblCatalogStaging
OPEN import_loop
FETCH NEXT FROM import_loop
INTO #curCatalogID,
#curNomenclature,
#curMainCategory,
#curSubCategory,
#curManufacturer,
#curModelNo,
#curPrice,
#curProductDesc,
#curImage,
#curPDFName,
#curInventory,
#curBatchID,
#curAuditID
WHILE ##FETCH_STATUS = 0
BEGIN
SET #nCnt = ##ROWCOUNT;
FETCH NEXT FROM import_loop
INTO #curCatalogID,
#curNomenclature,
#curMainCategory,
#curSubCategory,
#curManufacturer,
#curModelNo,
#curPrice,
#curProductDesc,
#curImage,
#curPDFName,
#curInventory,
#curBatchID,
#curAuditID
END
CLOSE import_loop
DEALLOCATE import_loop
SELECT #nCnt
It should just return 1 value of 2036 ( number of rows in the staging table ) but im getting back like 2036 rows affected, 4072 rows affected, etc etc
I'm not so sure ##ROWCOUNT is meant to be used inside a CURSOR.
You might have better luck with:
DECLARE #nCnt INT
SET #nCnt = 0
...
SET #nCnt = #nCnt + 1;
Note: A TRIGGER is probably the right place to be doing this validation on row insert/update. Unless you really only want the validation to happen sometimes. (Also, it's SQL errors you'll be raising, not exceptions)
i m not sure if its as simple as this but do you just want:
select count (*) FROM tblCatalogStaging
##Rowcount provides the number of rows that were affected by the last statemenet to be executed. I do not think this is what you want, and I would agree with ebyrob about just using a counter variable.
But that is if you really need to do this in a cursor. AS marc_s suggest, you may want to rework your actual procedure so that it is using sets. If that is not possible and you need to, as you said in your response, deal with exceptions in your loop, you may want to look at Phil Factors recent article on that topic.

t-sql replace on text field

I have hit a classic problem of needing to do a string replace on a text field in an sql 2000 database. This could either be an update over a whole column or a single field I'm not fussy.
I have found a few examples of how to use updatetext to achieve it but they tend to be in stored procedures, does anyone know of a similar thing that is wrapped into a function so I can use it like I would usually use Replace(). The problem with the Replace() function for anyone who isn't aware is that it doesn't support text fields.
Edit: I realised I could probably get away with varchar(8000) so have swapped the fields to this type which fixes the issue. I never found a true solution.
Here is the sample query to update table with text column using REPLACE function. Hope this is useful for you.
UPDATE <Table> set textcolumn=
REPLACE(SUBSTRING(textcolumn,1,DATALENGTH(textcolumn)),'findtext','replacetext')
WHERE <Condition>
I am afraid you cannot do it within a function
When you try to declare a function like:
create function dbo.textReplace(
#inText as text)
returns text
as
begin
return 'a' -- just dummy code
end
You will get the following error:
The text data type is invalid for return values.
In other words you could not write a simple equivalent of REPLACE function for the text data type
This is my code snippet for this scenario:
DECLARE #oldtext varchar(1000)
DECLARE #newtext varchar(1000)
DECLARE #textlen int
DECLARE #ptr binary(16)
DECLARE #pos int
DECLARE #id uniqueidentifier
SET #oldtext = 'oldtext'
SET #newtext = 'newtext'
SET #textlen = LEN(#oldtext)
DECLARE mycursor CURSOR LOCAL FAST_FORWARD
FOR
SELECT [UniqueID]
,TEXTPTR([Text])
,CHARINDEX(#oldtext, [Text]) - 1
FROM [dbo].[myTable]
WHERE [Text] LIKE '%' + #oldtext +'%'
OPEN mycursor
FETCH NEXT FROM mycursor into #id, #ptr, #pos
WHILE ##fetch_status = 0
BEGIN
UPDATETEXT [dbo].[myTable].Text #ptr #pos #textlen #newtext
FETCH NEXT FROM mycursor into #id, #ptr, #pos
END
CLOSE mycursor
DEALLOCATE mycursor
You would have to cast the text field to a varchar(8000) or nvarchar(4000) if you are replacing over an ntext field.
MyField = REPLACE(CAST(MyField as VARCHAR(4000)), "string1", "string2")
This ofcourse will only work if you can guarantee the content in the field is <= 4000/8000 characters in length.
You can also use the SUBSTRING() function, which returns a varchar when passed a text value.
For instance:
MyVarchar = SUBSTRING(myTextField, 1, DATALENGTH(myTextField))
If you're populating a varchar with a specific length, you can truncate to fit:
MyVarchar100 = SUBSTRING(myTextField, 1, 100)

Resources