Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Monday, November 16, 2015

How doing a case sensitive search in SQL Server?

Question: How doing a case sensitive search in SQL Server?
Answer:
If Column1 of Table1 has following values ‘CaseSearch, casesearch, CASESEARCH, CaSeSeArCh’, following statement will return you all the four records.
SELECT Column1FROM Table1WHERE Column1 'casesearch'
To make the query case sensitive and retrieve only one record (“casesearch”) from above query, the collation of the query needs to be changed as follows.
SELECT Column1FROM Table1WHERE Column1 COLLATE Latin1_General_CS_AS 'casesearch'
Adding COLLATE Latin1_General_CS_AS makes the search case sensitive.
Default Collation of the SQL Server installation SQL_Latin1_General_CP1_CI_AS is not case sensitive.
To change the collation of the any column for any table permanently run following query.
ALTER TABLE Table1ALTER COLUMN Column1 VARCHAR(20)COLLATE Latin1_General_CS_AS
To know the collation of the column for any table run following Stored Procedure.
EXEC sp_help DatabaseName
Second results set above script will return you collation of database DatabaseName.
Thanks @PinalDave for the beautiful post.

Thursday, October 8, 2015

TSQL Query for Global Search in Database

Hello Friends,

          2 months back I was looking for a string saved in database from my application. Suddenly I found that the string value was not saved in expected SQL table. However the application-logs had no logs for any error raised by insert query.

          I was surprised and wondering where the hell my string value stored in database of approx. 15 GB of size and approx. 108 tables.

          Finally to help myself, I prepared a TSQL script that helps me to find a varchar-value among any table from a database. Later I extended the same script to support seeking multiple databases. 

          You just need to specify @Text_To_Search, @DBname and a flag - @Single_DB_Only to indicate whether to seek in single database OR all databases on the sql-server.

SET NOCOUNT OFF
GO

declare @Text_To_Search nvarchar(max)
declare @TableName nvarchar(max)
declare @ColName nvarchar(max)
declare @CMD nvarchar(max)
declare @DBname nvarchar(max)
declare @Single_DB_Only bit

 
set @Text_To_Search = 'SOMETHING'   -- Enter the Text here which you want to search
set @Single_DB_Only = 1     -- If @Single_DB_Only = 0 then the search will be in only one database
if @Single_DB_Only = 1
 set @DBname = 'MY_DATABASE'    -- Enter Database Name in which you want to search
 

/* ********************** Validation ********************** */
IF @Single_DB_Only = 1 AND NOT EXISTS(SELECT name FROM [master].[sys].[databases] WHERE name = @DBname)
BEGIN
 PRINT 'Please enter valid database name'
 RAISERROR('Please enter valid database name', 20, -1) WITH LOG
END
/*-- ********************** Validation ********************** */
 
if exists(select * from [master].[dbo].sysobjects where xtype = 'U' and [Name] = 'MY_INFO_ALL_TABLES')
  drop table [master].[dbo].MY_INFO_ALL_TABLES
create table [master].[dbo].MY_INFO_ALL_TABLES (TableName nvarchar(max), ColName nvarchar(max))
 
if exists(select * from [master].[dbo].sysobjects where xtype = 'U' and Name = 'MY_INFO')
  drop table [master].[dbo].MY_INFO
create table [master].[dbo].MY_INFO (DBName nvarchar(max), TableName nvarchar(max), ColName nvarchar(max), FieldValue nvarchar(max))

if @Single_DB_Only = 0
Begin
 declare CUR_DB cursor for select name from [master].[sys].[databases] where name not in('master','tempdb', 'model','msdb','tempdb') and state = '0' 
 open CUR_DB
 fetch next from CUR_DB  into @DBname
 while @@FETCH_STATUS = 0
 Begin
  print @DBNAME 
  
  set @CMD = 'insert into [master].[dbo].MY_INFO_ALL_TABLES (TableName, ColName) select T1.Name as TableName , T0.Name as ColName from [{3}].sys.syscolumns T0 inner join [{3}].sys.sysobjects T1 on T0.id = T1.id where T1.xtype = ''U'' and T0.Name not like ''MY_TABLES%'' '
  set @CMD = replace(@CMD,'{3}',@DBname)
  -- print @CMD
  exec (@CMD)
  
  declare CUR cursor for select TableName , ColName from [master].[dbo].MY_INFO_ALL_TABLES
  open CUR
  fetch next from CUR  into @TableName, @ColName
  while @@FETCH_STATUS = 0
  Begin
     set @CMD = 'insert into [master].[dbo].MY_INFO (DBName,TableName,ColName,FieldValue) select ''{3}'',''{1}'',''{0}'', cast({0} as nvarchar) from [{3}].dbo.{1} where {0} like ''%{2}%'' '
     set @CMD = replace(@CMD,'{0}',@ColName)
     set @CMD = replace(@CMD,'{1}',@TableName)
     set @CMD = replace(@CMD,'{2}',@Text_To_Search)
     set @CMD = replace(@CMD,'{3}',@DBname)
     -- print @CMD
     exec (@CMD)
     fetch next from CUR into @TableName, @ColName
  End
  close CUR
  deallocate CUR
  
  fetch next from CUR_DB  into @DBname
 End
 close CUR_DB
 deallocate CUR_DB
End
Else
Begin
 print @DBNAME 
 
 set @CMD = 'insert into [master].[dbo].MY_INFO_ALL_TABLES (TableName, ColName) select T1.Name as TableName , T0.Name as ColName from [{3}].sys.syscolumns T0 inner join [{3}].sys.sysobjects T1 on T0.id = T1.id where T1.xtype = ''U'' and T0.Name not like ''MY_TABLES%'' '
 set @CMD = replace(@CMD,'{3}',@DBname)
 -- print @CMD
 exec (@CMD)
 
 declare CUR cursor for select TableName , ColName from [master].[dbo].MY_INFO_ALL_TABLES
 open CUR
 fetch next from CUR  into @TableName, @ColName
 while @@FETCH_STATUS = 0
 Begin
    set @CMD = 'insert into [master].[dbo].MY_INFO (DBName,TableName,ColName,FieldValue) select ''{3}'',''{1}'',''{0}'', cast({0} as nvarchar) from [{3}].dbo.{1} where {0} like ''%{2}%'' '
    set @CMD = replace(@CMD,'{0}',@ColName)
    set @CMD = replace(@CMD,'{1}',@TableName)
    set @CMD = replace(@CMD,'{2}',@Text_To_Search)
    set @CMD = replace(@CMD,'{3}',@DBname)
    -- print @CMD
    exec (@CMD)
    fetch next from CUR into @TableName, @ColName
 End
 close CUR
 deallocate CUR
 
 fetch next from CUR_DB  into @DBname
End
 
select * from [master].[dbo].MY_INFO
GO



          Hope this TSQL script can save a lot time of yours,

          Enjoy!!!

Heirarchical data - SQL query

Creating Table:

CREATE TABLE [Category](
 [CatId] [int] IDENTITY(1,1) NOT NULL,
 [PCatId] [int] NULL,
 [CatName] [varchar](50) NULL,
 CONSTRAINT [PK_Category] PRIMARY KEY CLUSTERED 
(
 [CatId] ASC
))
GO

Sample Data:

Insert into [Category] ([PCatId],[CatName]) values (0,'Cat1');
Insert into [Category] ([PCatId],[CatName]) values (0,'Cat2');
Insert into [Category] ([PCatId],[CatName]) values (1,'Cat3');
Insert into [Category] ([PCatId],[CatName]) values (1,'Cat4');
Insert into [Category] ([PCatId],[CatName]) values (2,'Cat5');
Insert into [Category] ([PCatId],[CatName]) values (2,'Cat6');
Insert into [Category] ([PCatId],[CatName]) values (0,'Cat7');
Insert into [Category] ([PCatId],[CatName]) values (7,'Cat8');
Insert into [Category] ([PCatId],[CatName]) values (7,'Cat9');
Insert into [Category] ([PCatId],[CatName]) values (7,'Cat10');
Insert into [Category] ([PCatId],[CatName]) values (8,'Cat11');
Insert into [Category] ([PCatId],[CatName]) values (8,'Cat12');
Insert into [Category] ([PCatId],[CatName]) values (8,'Cat13');
GO

Final SQL Query

Now, Get Category with CatId = 8 and all it's child-hierarchy :

declare @catId int = 8;

-- select * from Category;

WITH hierarchy AS (
  SELECT c1.CatId,
         c1.CatName,
         c1.PCatId,
         CAST(NULL AS VARCHAR(50)) AS parentname
    FROM Category c1
   WHERE c1.PCatId = 0
  UNION ALL
  SELECT c2.CatId,
         c2.CatName,
         c2.PCatId,
         y.CatName
    FROM Category c2
    JOIN hierarchy y ON y.CatId = c2.PCatId)
SELECT s.CatId,
       s.CatName,
    s.PCatId,
       s.parentname
  FROM hierarchy s
  where s.PCatId = @catId OR s.CatId = @catId
  order by s.PCatId

Get list of all foreign keys in SQL database

Hello friends,

Yesterday in free time I was just googling for a solution if I can get a single list of all foreign keys defined in my Microsoft SQL database. I found many articles and answers on stack-overflow, too.

Finally after compiling all those solutions I have created my own SQL script. So sharing the with you here with a hope that this may help someone.

SELECT
 FK_Table = FK.TABLE_NAME,
 FK_Column = CU.COLUMN_NAME,
 PK_Table = PK.TABLE_NAME,
 PK_Column = PT.COLUMN_NAME,
 Constraint_Name = C.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
 ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
 ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
 ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
   SELECT i1.TABLE_NAME, i2.COLUMN_NAME
   FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
   INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
    ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
   WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY') PT
  ON PT.TABLE_NAME = PK.TABLE_NAME
-- optional:
ORDER BY 1,2,3,4

Monday, October 5, 2015

EntityFramework Performance and AutoDetectChanges

What is Auto Detect Changes?

Entity framework has two methods of change detection built into the framework, Instant Notification and Snapshot. Most people seem to use the Snapshot mechanism as it is the easiest to configure and most well known. I will cover the Instant Notification (Proxy Entities) Mechanism in a later post.

Wednesday, July 24, 2013

SQL SERVER – Check If Column Exists in SQL Server Table

A very frequent task among SQL developers is to check if any specific column exists in the database table or not. Based on the output developers perform various tasks. Here arecouple of simple tricks which you can use to check if column exists in your database table or not.

Method 1

IF EXISTS(SELECT FROM sys.columnsWHERE Name N'columnName' AND OBJECT_ID OBJECT_ID(N'tableName'))BEGIN
PRINT 
'Your Column Exists'END  
For AdventureWorks sample database
IF EXISTS(SELECT FROM sys.columnsWHERE Name N'NameAND OBJECT_ID OBJECT_ID(N'[HumanResources].[Department]'))BEGIN
PRINT 
'Your Column Exists'END  

Method 2

IF COL_LENGTH('table_name','column_name'IS NOT NULLBEGIN
PRINT 
'Your Column Exists'END
For AdventureWorks sample database
IF COL_LENGTH('[HumanResources].[Department]','Name'IS NOT NULLBEGIN
PRINT 
'Your Column Exists'END

Method 3

IF EXISTS(SELECT TOP *FROM INFORMATION_SCHEMA.COLUMNSWHERE [TABLE_NAME] 'TableName'AND [COLUMN_NAME] 'ColumnName'AND [TABLE_SCHEMA] 'SchemaName')BEGIN
PRINT 
'Your Column Exists'END
For AdventureWorks sample database
IF EXISTS(SELECT TOP *FROM INFORMATION_SCHEMA.COLUMNSWHERE [TABLE_NAME] 'Department'AND [COLUMN_NAME] 'Name'AND [TABLE_SCHEMA] 'HumanResources')BEGIN
PRINT 
'Your Column Exists'END
Let me know if you know any other method to find if Column Exists in SQL Server Table.
Thanks to Pinal Dave.

Delete servers from the list on SQL Server 2012 - Logon Screen

You might have seen below screen countless times and you might wonder what is there isblog about in this simple screen. Well, continue reading and you would get the answer.
Many times, DBA have to login to production server from non-regular machine, may be a developer’s workstation. Once you login to SQL, do your work and close the management studio. Do you know that your server name is saved in management studio? Of course, very useful feature because you may not like to type server name/IP address every time. Whatever servers you have connected, it would be stored by management studio. Butsometime, it’s annoying!
What you would do if you want SQL Server Management Studio to forget “all” the servers listed in drop down of Server name? To do that, you need to know how and where it’s stored. You can use one of my favorite tool from sysinternals called Process Monitor (also known as ProcMon) and easily figure out that this is stored in a file under your windows user profile.
Below is the file in SQL 2008 R2 Management Studio.
%appdata%\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin
For SQL Server 2012, here is what we can see in ProcMon
So, the path is
%appdata%\Microsoft\Microsoft SQL Server\110\Tools\Shell\SqlStudio.bin
So far, you might wonder, where is the new feature? I have been asked by many users to delete entries from SSMS “Connect to Server” server name list. Well, unofficially, you can delete the file directly which we found via ProcMon. Note that delete file to get rid of server list is not officially supported by Microsoft.
Better way to achieve this is provided in SSMS 2012. To delete the servers from the list, highlight the name we want to delete (via keyboard or mouse) and then press delete key via keyboard. We can’t be multi-select and has to be done one by one. We can delete as many entries we want. I have delete few from first screenshot taken and here is the modified version.
This is not available in SQL 2008 R2 and its previous version. This came from feedback given to SQL Server Product group.
Hope you have learned something new today!

Monday, June 10, 2013

SQL SERVER – Reseed Identity of Table – Table Missing Identity Values – Gap in Identity Column

Hi Friends,

The search of this article was led by while I was finding an answer to my problem. [Which I have already posted here.]

Sometimes it is required to remove gaps in identity column series. In such situations this article can help people.

Read full article here...

Thanks,
Vihang Shah.

SQL SERVER – DBCC RESEED Table Identity Value – Reset Table Identity

Hi Guys,

Today I faced an issue, when I migrated data from 1 DB to another DB using simple insert queries on cross DBs via SQL Server Management Studio. The identity column created an issue for my case here. Then I realized to truncate table and start inserting new records, which leads me to a surprise of "IDENTITY NOT GETTING RESET" with new records.

Then, my surf starts and finally Mr. Pinal Dave answered me with his fantastic blog post here. Which taught me a good thing today of RESEEDING Table Identity Value.

I am writing this article just to share this to all my blog lovers & friends, so that this may help you, too.

Hope this will help all my friends,

Update:
Guys, I have also written another article on this topic here. May this also help you out.

Thanks,
Vihang Shah.

Wednesday, June 5, 2013

SQL SERVER – Script to Update a Specific Column in Entire Database

“Pinal,
In our database we have recently introduced ModifiedDate column in all of the tables. Now onwards any update happens in the row, we are updating current date and timeto that field.
Now here is the issue, when we added that field we did not update it with a default value because we were not sure when we will go live with the system so we let it be NULL. Now modification to the application went live yesterday and we are now updating this field.
Here is where I need your help. We need to update all the tables in our database where we have column created ModifiedDate and now want to update with currentdatetime. As our system is already live since yesterday there are several thousands of the rows which are already updated with real world value so we do not want to update those values. Essentially, in our entire database where ever there is a ModifiedDate column and if it is NULL we want to update that with current date time? 
Do you have a script for it?”
For reply read here...

Thursday, December 20, 2012

SQL SERVER – Select and Delete Duplicate Records

Developers often face situations when they find their column have duplicate records and they want to delete it. A good developer will never delete any data without observing it and making sure that what is being deleted is the absolutely fine to delete. Before deleting duplicate data, one should select it and see if the data is really duplicate.

A very nice post & video. Read more here.

Saturday, November 12, 2011

What's up with SQL Server 2008 Express editions

 Microsoft has announced the release of SQL Server 2008 and that means it time for another post about SQL Server Express.
The press release indicated that SQL Express is already available, but those of you who have followed the link have found that it is not actually there. Nothing to worry about, has a dependency on the .NET Framework 3.5 SP1 and we need to coordinate the release to the web for both of these which will take a few more days. I'll blog about it when we release it and you can watch the Express web site for updates; when we release it, it will be available from that site.
There will be three editions of SQL Express, each one adding to the functionality of the previous one; you simply pick the edition that includes the set of functionality you need and install it. The information I posted about SQL Express RC0 is still valid, but I'm reproducing the feature comparison table here to include the third edition:
Feature
SQL Server 2008 Express
SQL Server 2008 Express with Tools
SQL Server 2008 Express with Advanced Services
Management



PowerShell Integration
Y (Separate installation)*
Y
Y
Policy Based Management
Y (manual only)**
Y (manual only)*
Y (manual only)**
Management Studio Basic
N
Y
Y
SQL Engine



Integrated Full Text Search
N
N
Y
Merge & Upsert
Y
Y
Y
New Data type support



Filestream support
Y
Y
Y
New Date & Time data types
Y
Y
Y
Geodetic data types
Y
Y
Y
Advanced Spatial Libraries
Y
Y
Y
Support for Spatial Standards
Y
Y
Y
New Tools



Import/Export Wizard
Y
Y
Y
Replication



Change Tracking
Y
Y
Y
Synchronization Services
Y (Separate installation)***
Y (Separate installation)***
Y
Reporting Services



Increase RS Memory Limit
N
N
Y
RS Word/Rich Text Export
N
N
Y
IIS Agnostic Report Deployment
N
N
Y
Enhanced Gauges & Charting
N
N
Y
Business Intelligence Developer's Studio
N
N
Y
* The SqlPS command line tool can be enabled in SQL Express by installing Windows PowerShell 1.0 before installing SQL Express.
** Policies can be created in SQL Express and run manually. There is no support for automated policy based management.
*** Synchronization Services support in SQL Express requires that you install the component separately from the SQL Server 2008 Feature Pack.
As you can see, SQL Express with Tools includes the core database engine and the basic version of Management Studio; this is the ideal edition for people who want the right tools for developing relational database applications. The advanced features such as Integrated Full Text Search, Reporting Services and BIDS are available in SQL Express Advanced. SQL Express with Tools will be delivered in the same architectures and with the same prerequisites as SQL Express Advanced, which are as follows:
SQL Express with Tools architecture

32-bit only installation package (x86 platforms only)
64-bit native installation packages (x64 platforms only)



SQL Express with Tools Prerequisites
.NET Framework 3.5 SP1
Windows Installer 4.5
Windows PowerShell 1.0
As with previous releases (SQL Server 2005) we will be releasing SQL Express 2008 in stages. SQL Express core will be released first, along with Visual Studio 2008 SP1, and the other two editions will follow about a month later. As I said, watch the Express web site and this blog for information about the release of these two additional editions.

- Vihang

Find a cool free stuff everyday

Giveaway of the Day

Hiren Bharadwa's Posts

DotNetJalps