Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Posts Tagged ‘T SQL’

What is wrong with IsNumeric()?

Posted by Viral Sarvaiya on May 18, 2012

Today I face very strange thing with IsNumeric() function in sql

select IsNumeric('1234D234')
select IsNumeric('123A123')

Both query have alphanumeric value and both give different answer. very strange.

After a long time spent on google i get solution. We can say or cannot say that there are bug in IsNumeric() function.

IsNumeric() can falsely interpret non-numeric letters and symbols (such as D, E, and £, $), and even tabs (CHAR(9)) as numeric.

With this character, Why IsNumeric() can not give right answer? because D stand for Decimal. that value consider as a decimal value, E stand for exponential and $,£ is stand for currency symbol. so Isnumeric() fail to convert those values which has like D,E,$,£ characters.

so to get around this problem, we can create user define function which find the value is integer/numeric. as below.

CREATE FUNCTION dbo.CheckNumeric
(
@num VARCHAR(64)
)
RETURNS BIT
BEGIN
IF LEFT(@num, 1) = '-'
SET @num = SUBSTRING(@num, 2, LEN(@num))

DECLARE @pos TINYINT

SET @pos = 1 + LEN(@num) - CHARINDEX('.', REVERSE(@num))

RETURN CASE
WHEN PATINDEX('%[^0-9.-]%', @num) = 0
AND @num NOT IN ('.', '-', '+', '^')
AND LEN(@num)>0
AND @num NOT LIKE '%-%'
AND
(
((@pos = LEN(@num)+1)
OR @pos = CHARINDEX('.', @num))
)
THEN
1
ELSE
0
END
END
GO

Or

CREATE FUNCTION dbo.CheckInteger
(
@num VARCHAR(64)
)
RETURNS BIT
BEGIN
IF LEFT(@num, 1) = '-'
SET @num = SUBSTRING(@num, 2, LEN(@num))

RETURN CASE
WHEN PATINDEX('%[^0-9-]%', @num) = 0
AND CHARINDEX('-', @num) <= 1
AND @num NOT IN ('.', '-', '+', '^')
AND LEN(@num)>0
AND @num NOT LIKE '%-%'
THEN
1
ELSE
0
END
END
GO

Learn From: http://classicasp.aspfaq.com/general/what-is-wrong-with-isnumeric.html
Thanks.

Posted in Sql Server | Tagged: , , , , | 3 Comments »

SPACE() function of SQL Server

Posted by Viral Sarvaiya on February 16, 2012

Usually when we concatenate two fields like firstname and lastname we use ‘ ‘ between them like below

select firstname + ' ' + lastname from tblEmployee

And if we want more space then we use long space between them, but sql server provide function for print space between query.

Syntax:
SPACE(NO)

For example

select firstname + SPACE(2) + lastname from tblEmployee

It will return like below.

Viral  Sarvaiya

Thanks.

Enjoy..

Posted in Sql Server | Tagged: , , , , | Leave a Comment »

RESEED/Reset Table Identity Value in sql server

Posted by Viral Sarvaiya on January 6, 2012

DBCC CHECKIDENT can reset the identity value of the table,

For example if table has 500 reords and not we want to delete all records or want to start data from 600 then this command will help us.

DBCC CHECKIDENT (Table_name, reseed, 0)

OR

DBCC CHECKIDENT (Table_name, reseed, 600)

Most of our identity we start with 1 so must have to take care that identity set to 0.

If identity is set below values that currently are in table, it will violate the uniqueness constraint as soon as the values start to duplicate and will generate error.

Enjoy…

Posted in Sql Server | Tagged: , , , , , , , , , , , | Leave a Comment »

Remove duplicate records from the database table

Posted by Viral Sarvaiya on October 18, 2010

In my recent post http://viralsarvaiya.wordpress.com/2010/09/27/removing-duplicate-records-from-datasetdatatable/, I explain how to remove duplicate records form the dataset or datatable.

But if you want to delete duplicate records directly from the database then…..
First find the duplicate records,


SELECT MAX(ID) as ID, Name, Company FROM Employee GROUP BY Name, Company HAVING COUNT(*) > 1

This records give me the total duplicate records

Now to delete the duplicate records,


DELETE FROM Employee WHERE ID IN (SELECT MAX(ID) FROM Employee GROUP BY Name, Company HAVING COUNT(*) > 1)

Enjoy Coding…..

Posted in Sql Server | Tagged: , , , | Leave a Comment »

Calculating Work-Days in T-SQL

Posted by Viral Sarvaiya on May 3, 2010

Overview

One of the more serious questions in project scheduling, employee planning, and accounting of time is “How many workdays are there?” In other words, given a start date and an end date, how many weekdays (usually a “workday”) are there in the date range including the start date and the end date?

The normal response I get to that question varies but has been limited to “It can’t be done in SQL”, “Ya gotta use a CURSOR”, or “You have to build a table”. This article will take you through all of the logic behind building a nasty fast “Work Day Calculator” function, the crux of which is a single SELECT statement. A fully commented production-worthy UDF is available at the end of this article.

For more details :

http://www.sqlservercentral.com/articles/Advanced+Querying/calculatingworkdays/1660/

Posted in Sql Server | Tagged: , , | Leave a Comment »

Date Manipulation with DATEADD/DATEDIFF

Posted by Viral Sarvaiya on April 7, 2010

Many times when working with date types in SQL we need to remove the time portion and leave just the date. There are a number of ways to accomplish this, but this article will focus on my favorite, the DATEADD/DATEDIFF

for more details click here

http://www.sqlservercentral.com/articles/Date+Manipulation/69694/

Posted in Sql Server | Tagged: , , , | Leave a Comment »

List of Table Constraints in sql server

Posted by Viral Sarvaiya on November 18, 2009

There five type of constrains provided by SQL Server. We shall see each one of then in details

1. Primary Key Constraint

A primary key is used to uniquely identify each row in a table. A primary key can consist of one or more then more columns in table. When they consist of more then one column they are called composite key. It ensures unique non-null key.


CREATE TABLE Student(
StudID INT PRIMARY KEY,
StudName VARCHAR(50)
)

or


ALTER TABLE Department ADD PRIMARY KEY (DeptID)

2. Foreign Key Constraint

A foreign key is a field in a table that matches the primary key column of another table. It establishes and enforces a link between data of two tables. It ensures that value points to a valid key.


CREATE TABLE Subjects(
SubID INT,
SubName VARCHAR(50),
StudID INT FOREIGN KEY REFERENCES Student(StudID),
TotalMarks INT,
)

or


ALTER TABLE Subjects(ADD CONSTRAINT StudID_Fk
FOREIGN KEY (StudID) REFERENCES Student(StudID)

3. Unique Constraint

It is similar to Primary Key Constraint. It ensures that every value in the column is unique value. It allows one NULL value.


CREATE TABLE Employee(
EmpID INT,
FirstName VARCHAR(50),
LastName VARCHAR(50),
DeptID INT,
Salary INT,
ProjectCode INT UNIQUE,
)

or


ALTER TABLE Employee ADD UNIQUE (ProjectCode)

4. Nullability Constraint

It defines whether a column will accept a NULL value or not. It is referred to as nullability of the column.


CREATE TABLE Employee(
EmpID INT,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50),
DeptID INT,
Salary INT,
ProjectCode INT
)

or


ALTER TABLE Employee ALTER COLUMN FirstName VARCHAR(50) NOT NULL;

5. Check Constraint

Check Constraint is extensively used to enforcement of general data-validation rules or simple business rules. Such as correct date range, max value that can be inserted into a table, etc.


CREATE TABLE Employee(
EmpID INT,
FirstName VARCHAR(50),
LastName VARCHAR(50),
DeptID INT,
Salary INT,
ProjectCode INT,
CONSTRAINT chk_sal CHECK (Salary BETWEEN 1000 AND 25000)
)

or


ALTER TABLE Employee
ADD CONSTRAINT chk_salary CHECK (Salary BETWEEN 1000 AND 25000)

Now in the below example show the all the Constraints in one table,


CREATE TABLE Employee(
EmpID INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50),
DeptID INT FOREIGN KEY REFERENCES Department(DeptID),
Salary INT,
ProjectCode INT UNIQUE,
CONSTRAINT chk_salary CHECK (Salary BETWEEN 1000 AND 25000)
)

Posted in Sql Server | Tagged: , , , , , , , , , , , , , | 2 Comments »

 
Follow

Get every new post delivered to your Inbox.