Showing posts with label t-sql. Show all posts
Showing posts with label t-sql. Show all posts

Using Variables in TOP clause in T-SQL

This is what I want to post as I heard so many people are facing this issue. We can use variables in T-SQL queries but, there are requirements that we may select only the top 5 rows or 10 rows or n rows from the result set and use them wherever needed. So, below is the implementation we have to use to achieve that.

  1. One way could be using a variable, which saves the complete t-sql query in it and execute that total query.
  2. Second way will be pass the variable dynamically to TOP clause.

I do not think the first way is feasible. So, I prefer to go to second way and below are the implementation details.

SQL SERVER 2005:

DECLARE @TOP INT;
SET @TOP = 10;
SELECT TOP (@TOP) * FROM [User]

If you observe the variable is what storing the value of how many values we need to select. from the table And the last statement is what the final query which does what we needed. Remember the brackets () around the @TOP variable are what must and should. I also failed to write the query very first time as I forgot to place the brackets around the @TOP variable.

Earlier Versions: SQL SERVER 2000:

DECLARE @TOP INT;
SET @TOP = 5;

SET ROWCOUNT @TOP;
SELECT * FROM [User];
SET ROWCOUNT 0; --DO NOT FORGET TO WRITE THIS. VERY IMPORTANT

There is nothing tricky here. Just setting the ROWCOUNT internal variable to the required value is what works for us. And the very important thing is do not forget to reset the value of ROWCOUNT back to 0. Otherwise it effects the other result sets which comes after these T-SQL statements.

I think you got what I am trying to say here and enjoy the nice tips and posts. Read More...

Check string contains numbers in T-SQL

I know this is looking very simple when we read. But, I had a requirement where I need to filter strings from string data type column in T-SQL. Means, some strings in database having numbers in them, and I need to get them out and do some processing. When I started implementing this, I had so many ideas and thought like, looping through all characters in each string and check whether it has numbers in it or not. But, this is not efficient and may be a stupid implementation. And after thought about it sometime, started reading T-SQL documentation and found a wonderful function which is already built in in T-sql. I am saved. Very happy to see that function and that is working very great.

The function name called "PATINDEX". Which requires two parameters. 1. Regular expression and another is 2. input string. It returns the value of the index where it finds the given expression. If it is greater than 0 then it found the match, otherwise no.

Usage:
DECLARE @inputStr Varchar(100);
SET @inputStr = 'This costs 35$';

IF PATINDEX('%[0-9]%',@inputStr) > 0
BEGIN
--Write some logic here
PRINT 'YES, The string has numbers';
END
ELSE
BEGIN
--Write some logic here.
PRINT 'NO, The string does not have numbers';
END

It's very simple. Right? Now, I can use this in the single SELECT query and using CASE, WHEN I can display all strings which has the numbers in it from a table.

And now, vice versa.. How to find whether a string contains alphabets. [There are possibilities that in database may have bad data. The numbers are also stored in the string type. A very bad design, but when we got to working on these type of projects, we have to find a way to refine it and make it more reliable and efficient.] So, in the same code, just change the first parameter of PATINDEX from '%[0-9]%' to '%[a-z]%'. That's it. The expression change is what we need to do there. You can try with any expression as per your requirements and solve the problems.

Hope you like this post and still we need to know plenty of options already exists in technologies. Explore more and know more and save time. Read More...

Best Split UDF function with delimeter in T-SQL to return result as a table

This is what the function I am using since many years to get the table of values in the given ID's which are separated by some delimiter.

Simple to understand and see the example in the comments in below function.
From the UI there are sometimes need of sending the data or ID's in the string format separated by a delimiter. So, in database, we need to grab them and apply some operations like with the ID's we need to get the records from a table. In this case, we need to use this UDF function. Everyone knows that inner joins are far better than IN clause or something else. So, what the approach I have taken here is, I will get the delimited string and delimiter and pass them to UDF function. It returns me a table which has the rows consists of the ID's. By using this table, I will apply whatever operation I want and get the result.

UDF Function:

GO
/****** Object:  UserDefinedFunction [dbo].[fnStringSplitter]    Script Date: 04/04/2006 11:44:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*******************************************************************************************************/
--            Author: Praveen Battula
--            Date: 04/04/2006                     /*******************************************************************************************************/
CREATE Function [dbo].[fnStringSplitter]
(   
    @IDs Varchar(max) --A big string which may have delimeter in it or not
    ,@Delimiter Varchar(1) -- Delimeter to use for splitting up the given string
)
/*********************** RETURN *********************/
--Returns the table with specific values in a temporary table. Useful especially if you have any IDs in the
--given string and want to get them as a table row values.
-- Example:
--@IDs = 1,2,3,4,5,6,7,8,9,10
--@Delimeter = ','
--Returns @Tbl_IDS, which is having 10 rows with above IDS in each row by splitting up with given delimeter [in this example ',']
/****************************************************/
Returns @Tbl_IDs Table (ID Varchar(500)) As
Begin
    --Remove the leading delimiter if any
    while (substring(@IDs,1,1) =@Delimiter)
        set @IDs = substring(@IDs, 2,len(@IDs)-1)

    -- Append comma
    Set @IDs = @IDs + @Delimiter

    -- Indexes to keep the position of searching
    Declare @Pos1 Int
    Declare @pos2 Int
    Declare @RowNum Int

    -- Start from first character
    Set @Pos1=1
    Set @Pos2=1
    While @Pos1
    Begin
        Set @Pos1 = CharIndex(@Delimiter,@IDs,@Pos1)
        Insert @Tbl_IDs Values (Substring(@IDs,@Pos2,@Pos1-@Pos2))
        -- Go to next non comma character
        Set @Pos2=@Pos1+1
        -- Search from the next charcater
        Set @Pos1 = @Pos1+1
    End
    Return
End

This is not a very complex logic to understand. And below is the usage of the function.
DECLARE @EmployeeIDs VARCHAR(MAX);
SET @EmployeeIDs = '1,2,3,4,5,6,7,8,9,10';
SELECT * FROM [Employee] as e INNER JOIN  dbo.fnStringSplitter(@EmployeeIDs, ',') as eIDs ON e.EmployeeID = eIDs.ID;

So, here I have passed a string which consists of IDs to the UDF function along with delimiter as second parameter and it returns me the table with IDs as records. Now, I am simply applying the inner join on the primary table and getting what actually I need. Very simple concept and implementaion.

Hope you like this function and please let me know, if you have any ways to improve this or issues with it. Read More...

Know COUNT of bit column using Group by in T-SQL

Here is a scenario most of the times we use and look for. I have a bit column in database table and want to filter the count of true count and false count by applying Group By on it. For example, below is the simple scenario I came up with to better present you.

We are storing employee details in database and taking attendance once in every day. So, in reporting, I want to see month wise report on how many are total, absent and present. Now, the challenge is need to find out how many are total employee and among them how many are attended and how many are absent in the given month and year.

OK, let's go to implementation and find the solution.

SELECT [Month],[Year],Count(IsPresent) as [Total], Count(Case When IsPresent='True' Then IsPresent End) as Attended, Count(Case When IsPresent='False' Then IsPresent End) as Absent From [EmployeeAttendance] WHERE [Month] = @Month AND [Year] = @Year GROUP BY [Month],[Year]

This is it!!! Very simple. Hope you understand it on how to apply grouping on bit field to find out the counts. Read More...

Compare Date only in Datetime field in T-SQL

This is simple still I want to share as this is asked by so many people around. So, here is the scenario why it's needed. [Mainly in reporting.]

From the UI, users selects the date and by using that date we need to compare the datetime field in database and produce some result. But, in database it actually the datetime field, we can't apply equal operator on it as it fails to do it because of time part.

I know, now there is a need of time for thinking on how to do it.

Solution:
SELECT * FROM [Employee] WHERE Convert(date,DateSent) = Convert(date,@Date);

OR

SELECT * FROM [Employee] WHERE DATEADD(dd,(DATEDIFF(dd,0,DateSent)),0) = DATEADD(dd,(DATEDIFF(dd,0,@Date)),0);

So, in above query we have taken out the Date part from both DateSent field in database and @Date parameter from the UI  and comparing them. Which produces exact result as we are looking for.

Hope this helps and want to know are there any better solutions for it. Read More...

Group By Date Time without milliseconds in T-SQL

There are lot of requirements which needs some complex logic and put maximum effort to implement them. The below scenario is the one I want to explain in writing T-SQL queries.

The requirement is very simple, I want to apply group by on DateTime field in database which does not includes the milliseconds part from the time. So, on the UI I need to group by and show records with seconds and but not with milliseconds.

In my first try, I just wrote the T-SQL query by directly applying the GROUP BY clause on the DateTime field and found that milliseconds are also including. Which is not matching with what exactly I was looking for. So, tested lot of scenarios and nothing works. I am out of ideas on how to trim the milliseconds and apply group by.

After spent some good time on it, got an idea and not sure this is the best and efficient way of implementing.

SELECT CAST(CAST(CONVERT(Date,Datesent) AS Varchar(20)) + ' ' + CAST(CONVERT(TIME(0),Datesent) AS Varchar(20)) AS Datetime) AS DateSent,
Name, Department,
    FROM [EmployeHistory]
    WHERE EmployeID = @EmployeID
    GROUP BY CAST(CAST(CONVERT(Date,Datesent) AS Varchar(20)) + ' ' + CAST(CONVERT(TIME(0),Datesent) AS Varchar(20)) AS Datetime),
Name, Department
ORDER BY DateSent Desc

So, in the above query, if you observe take the GROUP BY clause out and analyze it.
GROUP BY CAST(CAST(CONVERT(Date,Datesent) AS Varchar(20)) + ' ' + CAST(CONVERT(TIME(0),Datesent) AS Varchar(20)) AS Datetime)

I am doing some way to get  the things work out. :) So, don't be surprise. I am doing nothing here, other than taking the Date part from the date time and taking the Time part from the date time without milliseconds and finally casting it back to date by clubbing those two back...

Do you think, this is the best and efficient way? I am sure this will work without any issues. But, the main thing is even though it is looking like simple it took me time to get the solution for it. Hope this helps and please let me know, if you know any better solution than this. Read More...

How to generate random numbers in t-sql?

How to generate random numbers in t-sql? Is there any built-in logic or keyword for Random? Yes, the answer is below.
DECLARE @mx int, @mn int;
SELECT @mx = MAX(EmployeeID) FROM Employee;
SELECT @mn = MIN(EmployeeID) FROM Employee;
SELECT EmployeeID,EmployeeName FROM Employee WHERE EmployeeID = ROUND(@mn + (RAND() * (@mx-@mn)),0);
RAND() is the function which gives you the random number between 0 and 1. So, depends on the minimum and maximum numbers, it will give you the random number. Hope this is what you are looking for. Read More...

How to write inner join in update query T-SQL

When we are very new to t-sql, we generally face a problem like how to make a query to update a table by doing inner join. if you don't know this, your queries become very complex. Below is the example how to write that.

Where it can be useful is,
for example, some how db admin created a table called State, where he is using the StateName as the foreign key instead of the StateID to employee table. Now he wants to update the State column in employee table with the StateID from StateName, we need this inner join in update query.
//Syntax:
Update Table1 set columnName = pt.columnName
from Table1 d
inner join Table2 pt on d.columnName = pt.ColumnName

//Example:
Update Employee set State = s.StateID
from Employee e
inner join State s on e.State = s.StateName
Read More...

How to changes column size and column name through t-sql

Alter a column size in a table:

Syntax: Alter Table TableName Alter Column ColumnName DataType(Size)

Example: Alter Table dbo.[AddressType] Alter Column [Address] nvarchar(512);

Change ColumnName, DataType in a Table:
In t-sql, if we want to change the column name and data type as well, then it's some what complex than any other alter statements, below explain the process of how to change the column name as well as the data type change.

Syntax:
--Changing the column name.
Alter Table TableName Alter Column ColumnName DataType NULL/NOT NULL

EXEC sp_rename //Stored Procedure.
@objname = ' TableName. OldColumnName’,
@newname = 'New ColumnName',
@objtype = 'COLUMN'

Example:
Alter Table AddressType Alter Column Address VARCHAR(512) NULL

EXEC sp_rename
@objname = 'AddressType.Address',
@newname = 'Address1',
@objtype = 'COLUMN'

How good it is? Did you find any best way other than this? Read More...

How to Create/Drop an index in a table through t-sql

Create an Index in a Table:

Syntax: CREATE INDEX [IndexName]
ON [dbOwner].[TabelName] ([ColumnName])
WITH ( ALLOW_PAGE_LOCKS = OFF)
ON [PRIMARY]

Example: CREATE INDEX [UQ_DateCreated]
ON [dbo].[Contact] ([DateCreated])
WITH ( ALLOW_PAGE_LOCKS = OFF)
ON [PRIMARY]

Drop an Index in a Table:

Syntax: DROP INDEX [IndexName] on dbOwner.TableName

Example: DROP INDEX [IX_Content] on dbo.Content Read More...

How to add a column and set primary key in a table through t-sql

Add a Column to a Table:

Syntax: ALTER TABLE TableName add columnName DataType NULL/NOT NULL

Example: ALTER TABLE Employee add IsDeleted bit NULL

Add a Primary Key To aTable:

Syntax: ALTER TABLE TableName add PRIMARY KEY(ColumnName)

Example: ALTER TABLE AddressType add PRIMARY KEY(AddressTypeID)

Note: PrimaryKey:Don’t Allow duplicates. Read More...

How to set Foreign key through sql script

Syntax:
ALTER TABLE TableName
ADD CONSTRAINT ConstraintName
FOREIGN KEY (ColumnInFirstTable)
REFERENCES ReferenceTable(ColumnName)

Example:
ALTER TABLE Employee
ADD CONSTRAINT Fk_Employee_AddressType
FOREIGN KEY (AddressTypeID)
REFERENCES AddressType (AddressTypeID)

Note: The column AddressTypeID should be a primary key in both tables. Read More...

How to know the number of days in a month in t-sql

Some times we can get requirement to know the number of days in a given month. For example, while calculating how many days remaining in a month or last day of month or any other scenarios.
Here is a small script that will give you the number of days for given month. Example purpose, i am retrieving month from the current date.

declare @numberOfDaysInMonth int;

set @numberOfDaysInMonth = DAY(DATEADD (m, 1, DATEADD (d, 1 - DAY(getdate()), getdate())) - 1);

Read More...

How to know month name from month index in t-sql

When I am working with reports, this is what every time I am looking for. Everyone gives date on the report as input, and I want display the month name on the report instead of month index [1-12]. So, how to do it?

please use the below script to get the name of the month by month index.
DateName(month, convert( datetime, '2007-' + cast(month(getdate()) as varchar(2)) + '-01', 120))

Here month(getdate()) returns the current month index from getdate() function. Hope this helps... Read More...
Related Posts with Thumbnails
GiF Pictures, Images and Photos