Showing posts with label SQL Server. Show all posts
Showing posts with label SQL Server. 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.

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'Name' AND 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 1 *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 1 *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

Send an Email Alert when SQL Server Agent Service Stops/Fails

Here is how you can setup an Alert to send you an Email when SQL Server Agent Server Stops or Fails.
As a matter of fact you can do this for any Service you want to Alert on.
Open computer management program –> Browse down to Services –> Scroll down on the right hand side to SQL Server Agent Service or the service you want to alert on failure.
Right Click the SQL Server Agent Service and Select Properties, then select Recovery page. Expand the drop down for First failure and Select ‘Run a Program’
At the bottom of the page under Run Program, Type in ‘PowerShell’ in the Program input box.
Copy the entire statement from below and paste into the Command line parameters box, make sure you change the To email, Mail server and from email as per your environment.
-Command ‘Send-MailMessage -To suleman@sqlish.com -Subject \”<Mention ServerName>:SQL Agent Stopped\” -Body \”Please look into the issue; Scheduled Jobs will not run if the SQL Server Agent Service remains stopped.\” -SmtpServer <your mail Server> -From suleman@sqlish.com’
Hit Ok to finish the setup.
To test stop the SQL Server Agent service and look for the email in your mailbox.

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, December 15, 2012

Entity Framework 6: Alpha2 Now Available

Entity Framework 6: Alpha2 Now Available:
The Entity Framework team recently announced the 2nd alpha release of EF6.   The alpha 2 package is available for download from NuGet. Since this is a pre-release package make sure to select “Include Prereleases” in the NuGet package manager, or execute the following from the package manager console to install it:
PM> Install-Package EntityFramework -Pre
This week’s alpha release includes a bunch of great improvements in the following areas:
  • Async language support is now available for queries and updates when running on .NET 4.5.
  • Custom conventions now provide the ability to override the default conventions that Code First uses for mapping types, properties, etc. to your database.
  • Multi-tenant migrations allow the same database to be used by multiple contexts with full Code First Migrations support for independently evolving the model backing each context.
  • Using Enumerable.Contains in a LINQ query is now handled much more efficiently by EF and the SQL Server provider resulting greatly improved performance.
  • All features of EF6 (except async) are available on both .NET 4 and .NET 4.5. This includes support for enums and spatial types and the performance improvements that were previously only available when using .NET 4.5.
  • Start-up time for many large models has been dramatically improved thanks to improved view generation performance.
Below are some additional details about a few of the improvements above:

Async Support

.NET 4.5 introduced the Task-Based Asynchronous Pattern that uses the async and await keywords to help make writing asynchronous code easier. EF 6 now supports this pattern. This is great for ASP.NET applications as database calls made through EF can now be processed asynchronously – avoiding any blocking of worker threads. This can increase scalability on the server by allowing more requests to be processed while waiting for the database to respond.
The following code shows an MVC controller that is querying a database for a list of location entities:
    public class HomeController : Controller
    {
        LocationContext db = new LocationContext();

        public async Task<ActionResult> Index()
        {
            var locations = await db.Locations.ToListAsync();

            return View(locations);
        }
    }
Notice above the call to the new ToListAsync method with the await keyword. When the web server reaches this code it initiates the database request, but rather than blocking while waiting for the results to come back, the thread that is processing the request returns to the thread pool, allowing ASP.NET to process another incoming request with the same thread. In other words, a thread is only consumed when there is actual processing work to do, allowing the web server to handle more concurrent requests with the same resources.
A more detailed walkthrough covering async in EF is available with additional information and examples. Also a walkthrough is available showing how to use async in an ASP.NET MVC application.

Custom Conventions

When working with EF Code First, the default behavior is to map .NET classes to tables using a set of conventions baked into EF. For example, Code First will detect properties that end with “ID” and configure them automatically as primary keys.
However, sometimes you cannot or do not want to follow those conventions and would rather provide your own. For example, maybe your primary key properties all end in “Key” instead of “Id”. Custom conventions allow the default conventions to be overridden or new conventions to be added so that Code First can map by convention using whatever rules make sense for your project.
The following code demonstrates using custom conventions to set the precision of all decimals to 5. As with other Code First configuration, this code is placed in the OnModelCreating method which is overridden on your derived DbContext class:
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Properties<decimal>()
                .Configure(x => x.HasPrecision(5));

        }
But what if there are a couple of places where a decimal property should have a different precision? Just as with all the existing Code First conventions, this new convention can be overridden for a particular property simply by explicitly configuring that property using either the fluent API or a data annotation.
A more detailed description of custom code first conventions is available here.

Community Involvement

I blogged a while ago about EF being released under an open source license.  Since then a number of community members have made contributions and these are included in EF6 alpha 2.
Two examples of community contributions are:
  • AlirezaHaghshenas contributed a change that increases the startup performance of EF for larger models by improving the performance of view generation. The change means that it is less often necessary to use of pre-generated views.
  • UnaiZorrilla contributed the first community feature to EF: the ability to load all Code First configuration classes in an assembly with a single method call like the following:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
       modelBuilder.Configurations
           .AddFromAssembly(
typeof(LocationContext).Assembly);

}
This code will find and load all the classes that inherit from EntityTypeConfiguration<T> or ComplexTypeConfiguration<T> in the assembly where LocationContext is defined. This reduces the amount of coupling between the context and Code First configuration classes, and is also a very convenient shortcut for large models.

Other upcoming features coming in EF 6

Lots of information about the development of EF6 can be found on the EF CodePlex site, including a roadmap showing the other features that are planned for EF6.
One of of the nice upcoming features is connection resiliency, which will automate the process of retying database operations on transient failures common in cloud environments and with databases such as the Windows Azure SQL Database.
Another often requested feature that will be included in EF6 is the ability to map stored procedures to query and update operations on entities when using Code First.

Summary

EF6 is the first open source release of Entity Framework being developed in CodePlex. The alpha 2 preview release of EF6 is now available on NuGet, and contains some really great features for you to try.
The EF team are always looking for feedback from developers - especially on the new features such as custom Code First conventions and async support. To provide feedback you can post a comment on the EF6 alpha 2 announcement post, start a discussion or file a bug on the CodePlex site.
Hope this helps,
Vihang

Friday, December 16, 2011

SQL Server 2012 Release Candidate arrives

Late last week Microsoft made available the first Release Candidate of SQL Server 2012 (previously codenamed Denali).
According to Microsoft, over 100,000 people downloaded the CTPs (Community Technology Previews) leading up to the release, the feedback from which has been put into the release candidate.
“SQL Server 2012 RC is the first release which is feature complete and represents an exciting milestone for customers and partners looking to experience the full value of SQL Server 2012” said the team. “As the foundation of the cloud-ready information platform, SQL Server 2012 will help organizations unlock breakthrough insights across the organization as well quickly build solutions and extend data across on-premises and public cloud backed by mission critical confidence.”
There are a number of improvements in SQL Server 2012 that enterprises and developers alike will be interested in. It includes “AlwaysOn” technology, which permits multiple readable database secondary servers for reporting and backup workloads as well as support for high availability in complex data types. It also has some significant speed boosts, CPU usage controls, Resource Governor for multi-tenancy environments and predictable resource allocation for these scenarios.
The RC is available today for anyone looking to have a go with all of the headline features in a production-ready package.

Tuesday, November 22, 2011

SQL Server 2012 RC0 - SQL Server 2012 Programmability and Cloud Enabled

Programmability

Microsoft SQL Server 2012 enables developers to be more productive and easily create the next generation of robust database solutions using the powerful SQL Server T-SQL programming language and rich data types that manage virtually any type of data all through a new unified developer experience that enables build once, deploy anywhere across on-premises and cloud.
Key Capabilities
  • New unified development experience across database, BI and web.
  • Choice in data storage with FileTable and Remote Blog Storage.
  • Improvements for blazing-fast Full-Text Search.
  • Expanded spatial support.

Powerful Tools

Create next generation database applications that support the most demanding end-user requirements.
New Unified Development Experience
  • SQL Server Data Tools unifies the development experience for database development.
  • A single integrated environment for database development across database, BI, and web for any SQL Server platform on and off premises within Visual Studio.
New Frameworks
  • Support for the Data-Tier Application Framework dramatically simplifies the development, deployment and management of database applications across on-premises and cloud.
SQL Language Improvements
  • SQL Server 2012 supports new Transact-SQL language improvements.
  • Simplify complex programming tasks and ease database migrations with improved support for ANSI SQL standards.

 

Rich Support for Content


Leverage SQL Server’s built-in data type support to easily manage relational and non-relational data as part of the database.
Choice in Data Storage
  • FileTable permits organizations to store unstructured files directly in the database table.
  • Remote Blog Storage allows management simplicity or externally on separate hardware for scalability.
Expanded Spatial Support
  • Spatial enhancements include:
  • Circular arcs on the ellipsoid (an industry first for relational database systems).
  • Support for full globe spatial objects.
  • Functional parity of geography and geometry data types.
  • Added spatial indexing performance.
FILESTREAM Improvements
  • Manages files and documents efficiently while leveraging SQL Server security and transaction support.
  • Improvements in SQL Server 2012 yield improved performance, manageability and availability.
New Statistical Semantic Search
  • Enables T-SQL developers to bring deep insight to the organization within non-structured data files stored in the SQL Server database.
  • Reveal previously undiscovered relationships across stored data.

 

New Delivery Options

Choose from an array of delivery options that best suits customer needs.
New Support For Desktops
  • SQL Server 2012 Express offers a new Local Database Runtime (LocalDb) deployment option.
  • Ideal for developers who need to redistribute an embedded database within their desktop application or tool.
Cloud On Your Terms
  • Build applications exclusively for the cloud, or hybrid applications that consume both on-premise and cloud services.
  • Windows Azure Platform offers powerful database and BI functionality delivered as a service.
New SQL Server Appliances
  • Microsoft is partnering with some of the industry’s most well-known and respected hardware OEM’s to offer a line of SQL Server appliances.
  • Targeting a variety of enterprise scenarios.
Better with Windows Server
  • SQL Server 2012 is designed to be the best database server for Windows Server.
  • Offering several points where capabilities are tightly woven.
For More Info Visit Here..

The Cloud-Ready Information and Intelligence Platform

SQL Server 2012 is a cloud-ready information platform that will offer organizations the agility to create and scale solutions quickly from server to private or public cloud.
Key Capabilities
  • Reduces complexity and accelerates time to solution through appliance and private or public cloud offerings.
  • Flexible deployment options on your terms – server to cloud.
  • Optimize IT and developer productivity across server and cloud with common tools.
  • Extend Data Anywhere across server and/or cloud with expansive developer technologies.

Developer Productivity

Take database development to the next level with SQL Server Data Tools.
Developer Productivity
  • An integrated development experience for developers building next-generation web, enterprise and data-aware mobile applications across on-premises and public cloud.
  • Provides both graphical and text-based experiences for designing databases, tables, stored procedures, entities, models, and schemas.
  • Learn more here.

Simplify Deployment

Simplify Database development and deployment across on-premises and the cloud. Allowing developers to build once; deploy and manage anywhere.
Data-tier Application Component Enhancements
  • Introduced in SQL Server 2008 R2, Data-tier Application (DAC) support across SQL Server and Visual Studio.
  • Helps IT and developers to more easily define and contain the schemas.
  • Supports applications, then deploys, imports, and exports DACs more easily across on-premises and public cloud.
Data-tier Application Component (DAC) Parity with SQL Azure
  • SQL Server 2012 and SQL Azure offer ‘anywhere support’ for moving a DAC database between SQL Server databases across server, private cloud or SQL Azure.
  • Enables customers to build once; deploy and manage anywhere.
  • Unprecedented flexibility across IT and developers.
  • Import and export services in the DAC framework enables archiving and migration scenarios between on-premise and cloud database servers.
  • Extract database schema as well as data and serialize it into a new logical and open archive format – a .bacpac file.
  • Import the .bacpac archive into another database server.

Extend Data Anywhere

Extend the reach of data beyond on premises applications to new devices and locations in the cloud.
OData
  • Provides a consistent and open data-feed to power multiple user experiences across the web, devices and desktop with Odata, an open protocol built on widely used web standards.
Data Sync
  • Enables new scenarios with SQL Azure DataSync, a cloud service which provides bi-directional data synchronization between databases across datacenter and cloud.
Data Market
  • Monetize accumulated data through SQL Azure DataMarket that allows organizations to publish data for purchase and consumption by other entities.

For More Info Visit Here..


SQL Server 2012 RC0

Find a cool free stuff everyday

Giveaway of the Day

Hiren Bharadwa's Posts

DotNetJalps