I was recently working on a query to auto generate a Column ID based on an IDENTITY column. I used computed columns to achieve this. If you too have a similar requirement, then here’s the query.
DECLARE @TT TABLE (
CandID as 'C-' + RIGHT('000' + CONVERT(varchar, CourseID),5),
CourseID int IDENTITY(1,1),
ReferrerName varchar(10)
)
INSERT INTO @TT VALUES ('Dhiraj')
INSERT INTO @TT VALUES ('Jack')
INSERT INTO @TT VALUES ('Kelly')
INSERT INTO @TT VALUES ('Kelly')
INSERT INTO @TT VALUES ('Jack')
INSERT INTO @TT VALUES ('Dhiraj')
SELECT * FROM @TT
OUTPUT
Observe how the values of the CandID column are autogenerated based on the values if the CourseID column.
Learning about Sql server2005/2008,SSIS,SSRS and SSAS
Tuesday, 21 December 2010
List all the Weekends of the Current Year using SQL Server
Sometime back, I had posted to Find the WeekEnds in this Quarter or Year using SQL Server 2005/2008. An anonymous user wrote back asking if there was a way to determine the first and last day of the current year and rewrite the same query. Well here it is:
DECLARE @StrtDate datetime
DECLARE @EndDate datetime
SELECT @StrtDate = DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)
SELECT @EndDate = DATEADD(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate() )+1, 0))
;WITH CTE (weekends)
AS
(
SELECT @StrtDate
UNION ALL
SELECT DATEADD(d,1,weekends)
FROM CTE
WHERE weekends < @EndDate
)
SELECT weekends from CTE
WHERE DATENAME(dw,weekends)
In ('Saturday', 'Sunday')
DECLARE @StrtDate datetime
DECLARE @EndDate datetime
SELECT @StrtDate = DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)
SELECT @EndDate = DATEADD(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate() )+1, 0))
;WITH CTE (weekends)
AS
(
SELECT @StrtDate
UNION ALL
SELECT DATEADD(d,1,weekends)
FROM CTE
WHERE weekends < @EndDate
)
SELECT weekends from CTE
WHERE DATENAME(dw,weekends)
In ('Saturday', 'Sunday')
Find Maximum Value in each Row – SQL Server
Here’s a simple and efficient way to find the maximum value in each row using SQL Server UNPIVOT
DECLARE @t table (id int PRIMARY KEY, col1 int, col2 int, col3 int)
-- SAMPLE DATA
INSERT INTO @t SELECT 1, 45, 2, 14
INSERT INTO @t SELECT 2, 8, 1, 12
INSERT INTO @t SELECT 3, 21, 20, 8
INSERT INTO @t SELECT 4, 8, 5, 2
INSERT INTO @t SELECT 5, 23, 49, 7
INSERT INTO @t SELECT 6, 19, 7, 5
INSERT INTO @t SELECT 7, 7, 7, 2
INSERT INTO @t SELECT 8, 14, 17, 2
-- QUERY
SELECT id, MAX(col) AS maxValue
FROM
(
SELECT id, col FROM @t
UNPIVOT
(col FOR ListofColumns IN (col1,col2,col3))
AS unpivott) AS p
GROUP BY id
DECLARE @t table (id int PRIMARY KEY, col1 int, col2 int, col3 int)
-- SAMPLE DATA
INSERT INTO @t SELECT 1, 45, 2, 14
INSERT INTO @t SELECT 2, 8, 1, 12
INSERT INTO @t SELECT 3, 21, 20, 8
INSERT INTO @t SELECT 4, 8, 5, 2
INSERT INTO @t SELECT 5, 23, 49, 7
INSERT INTO @t SELECT 6, 19, 7, 5
INSERT INTO @t SELECT 7, 7, 7, 2
INSERT INTO @t SELECT 8, 14, 17, 2
-- QUERY
SELECT id, MAX(col) AS maxValue
FROM
(
SELECT id, col FROM @t
UNPIVOT
(col FOR ListofColumns IN (col1,col2,col3))
AS unpivott) AS p
GROUP BY id
NVARCHAR(MAX) VS NTEXT in SQL Server
Here are some differences between nvarchar(max)/nvarchar and ntext in SQL Server
Nvarchar(max)/Nvarchar()
Ntext
Nvarchar(max) is supported only from version 2005 onwards Ntext is available in prior versions too
You can specify the length in advance for nvarchar datatype i.e. nvarchar(100), nvarchar(4000) You can't specify the length for Ntext datatype
All types of string functions such as left, right, len, etc. can be used for Nvarchar data type Only limited functions like substring, datalength are used for Ntext datatype
Nvarchar datatype can be used in local variables Ntext can't be used in local variables
Nvarchar datatype is available from version 2005 onwards and will be supported for further releases Ntext will be removed from future release of SQL Server and will be substituted by nvarchar(max) datatype
In one of the upcoming posts, I will tell you how to convert an Ntext column to Nvarchar(max) and some points to consider while doing so.
Nvarchar(max)/Nvarchar()
Ntext
Nvarchar(max) is supported only from version 2005 onwards Ntext is available in prior versions too
You can specify the length in advance for nvarchar datatype i.e. nvarchar(100), nvarchar(4000) You can't specify the length for Ntext datatype
All types of string functions such as left, right, len, etc. can be used for Nvarchar data type Only limited functions like substring, datalength are used for Ntext datatype
Nvarchar datatype can be used in local variables Ntext can't be used in local variables
Nvarchar datatype is available from version 2005 onwards and will be supported for further releases Ntext will be removed from future release of SQL Server and will be substituted by nvarchar(max) datatype
In one of the upcoming posts, I will tell you how to convert an Ntext column to Nvarchar(max) and some points to consider while doing so.
Temp Table VS Table Variable in SQL Server
Here are some differences between Temp Table and Table Variable in SQL Server
Temp Table Table Variable
Temp table is valid for a session.
For eg: when you run the following code
create table #temp(i int)
insert into #temp select 345
Go
create table #temp(i int)
insert into #temp select 345
Go
you will get an error Table variable has a statement-level scope. ie as soon as you execute the statement the scope is lost
For eg: when you run the following code
declare @t table(i int)
insert into @t select 45
GO
declare @t table(i int)
insert into @t select 45
GO
you will not get an error
It is possible to alter the temp table to add columns, idexes,etc It is not possible to alter a table variable
It is possible to truncate a temp table It is not possible to truncate a table variable
SELECT INTO method can be used for temp table
SELECT * INTO #temp from your_table
SELECT INTO method cannot be used for table variable. You get error for the following
SELECT * INTO @t from your_table
Temp table can be useful when you have a large amount of data For small set of data, table variables can be useful
Temp Table Table Variable
Temp table is valid for a session.
For eg: when you run the following code
create table #temp(i int)
insert into #temp select 345
Go
create table #temp(i int)
insert into #temp select 345
Go
you will get an error Table variable has a statement-level scope. ie as soon as you execute the statement the scope is lost
For eg: when you run the following code
declare @t table(i int)
insert into @t select 45
GO
declare @t table(i int)
insert into @t select 45
GO
you will not get an error
It is possible to alter the temp table to add columns, idexes,etc It is not possible to alter a table variable
It is possible to truncate a temp table It is not possible to truncate a table variable
SELECT INTO method can be used for temp table
SELECT * INTO #temp from your_table
SELECT INTO method cannot be used for table variable. You get error for the following
SELECT * INTO @t from your_table
Temp table can be useful when you have a large amount of data For small set of data, table variables can be useful
When to use STUFF instead of REPLACE – SQL Server
The STUFF function in SQL Server ‘inserts’ a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.
REPLACE on the other hand replaces all occurrences of a specified string value with another string value.
The STUFF function is useful when you are not sure of the characters to replace, but you do know the position of the character. I saw an excellent implementation of this function over here by GMastros and Even. Here’s the code with a practical usage of STUFF:
CREATE FUNCTION [dbo].[fn_StripCharacters]
(
@String NVARCHAR(MAX),
@MatchExpression VARCHAR(255)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
SET @MatchExpression = '%['+@MatchExpression+']%'
WHILE PatIndex(@MatchExpression, @String) > 0
SET @String = STUFF(@String, PatIndex(@MatchExpression,
@String), 1, '')
RETURN @String
END
SELECT dbo.fn_StripCharacters('a1$%s#22d&39#f4$', '^a-z')
as OnlyAlphabets
OUTPUT
REPLACE on the other hand replaces all occurrences of a specified string value with another string value.
The STUFF function is useful when you are not sure of the characters to replace, but you do know the position of the character. I saw an excellent implementation of this function over here by GMastros and Even. Here’s the code with a practical usage of STUFF:
CREATE FUNCTION [dbo].[fn_StripCharacters]
(
@String NVARCHAR(MAX),
@MatchExpression VARCHAR(255)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
SET @MatchExpression = '%['+@MatchExpression+']%'
WHILE PatIndex(@MatchExpression, @String) > 0
SET @String = STUFF(@String, PatIndex(@MatchExpression,
@String), 1, '')
RETURN @String
END
SELECT dbo.fn_StripCharacters('a1$%s#22d&39#f4$', '^a-z')
as OnlyAlphabets
OUTPUT
Make a T-SQL Query Sleep for a certain amount of time
At times, in test scenarios, you may want to emulate that a transaction or a T-SQL query takes ‘x’ amount of time. Well that is possible (although not with precision) in SQL Server (2005/2008) using the WAITFOR command.
Here’s an example of delaying query execution till a specified time interval has elapsed – let us say 10 seconds
USE Northwind
WAITFOR DELAY '00:00:10';
SELECT LASTNAME, FIRSTNAME FROM Employees;
As you can see, we used the WAITFOR statement with a DELAY option to delay code execution for 10 seconds.
There are a couple of things you should note about the WAITFOR statement
- WAITFOR does not accept date values, only time values are allowed
- In some scenarios, the delay specified by you may not exactly the same as the delay caused by WAITFOR
Here’s an example of delaying query execution till a specified time interval has elapsed – let us say 10 seconds
USE Northwind
WAITFOR DELAY '00:00:10';
SELECT LASTNAME, FIRSTNAME FROM Employees;
As you can see, we used the WAITFOR statement with a DELAY option to delay code execution for 10 seconds.
There are a couple of things you should note about the WAITFOR statement
- WAITFOR does not accept date values, only time values are allowed
- In some scenarios, the delay specified by you may not exactly the same as the delay caused by WAITFOR
Duplicate a Column in SQL Server
Here’s a very simple but useful post that shows how to duplicate an existing column in SQL Server.
Assuming we have the following table structure with data:
CREATE TABLE #TmpTable(ColA varchar(10))
INSERT INTO #TmpTable SELECT 'ValueOne'
INSERT INTO #TmpTable SELECT 'ValueTwo'
INSERT INTO #TmpTable SELECT 'ValueThree'
INSERT INTO #TmpTable SELECT 'ValueFour'
INSERT INTO #TmpTable SELECT 'ValueFive'
INSERT INTO #TmpTable SELECT 'ValueSix'
Now to duplicate ColA, use the following code:
ALTER TABLE #TmpTable
ADD ColB varchar(10)
GO
UPDATE #TmpTable
SET ColB = ColA
GO
SELECT * FROM #TmpTable
As you can see, we have added a new column to the Table and used a simple Update statement to duplicate ColA. If the column already exists, you can avoid the ALTER TABLE.
OUTPUT
Assuming we have the following table structure with data:
CREATE TABLE #TmpTable(ColA varchar(10))
INSERT INTO #TmpTable SELECT 'ValueOne'
INSERT INTO #TmpTable SELECT 'ValueTwo'
INSERT INTO #TmpTable SELECT 'ValueThree'
INSERT INTO #TmpTable SELECT 'ValueFour'
INSERT INTO #TmpTable SELECT 'ValueFive'
INSERT INTO #TmpTable SELECT 'ValueSix'
Now to duplicate ColA, use the following code:
ALTER TABLE #TmpTable
ADD ColB varchar(10)
GO
UPDATE #TmpTable
SET ColB = ColA
GO
SELECT * FROM #TmpTable
As you can see, we have added a new column to the Table and used a simple Update statement to duplicate ColA. If the column already exists, you can avoid the ALTER TABLE.
OUTPUT
Subscribe to:
Posts (Atom)