Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Everything / database / SQL-Server

SQL-Server

SQL-Server

Great Reads

by Suresh Dasari's
Auto Generate Code (CRUD) for 3 Layered architecture (Entity, Data Access & Business Layer) with Stored Procedures based on table design.
by Paul Rony
Programmer's Guide to Starting a Software Company and Building an Enterprise Application
by #realJSOP
You can also enclose your column name in brackets, like so: [Create Date]

Latest Articles

by Suresh Dasari's
Auto Generate Code (CRUD) for 3 Layered architecture (Entity, Data Access & Business Layer) with Stored Procedures based on table design.
by Paul Rony
Programmer's Guide to Starting a Software Company and Building an Enterprise Application
by #realJSOP
You can also enclose your column name in brackets, like so: [Create Date]

All Articles

Sort by Score

SQL-Server 

by Suresh Dasari's
Auto Generate Code (CRUD) for 3 Layered architecture (Entity, Data Access & Business Layer) with Stored Procedures based on table design.
by #realJSOP
You can also enclose your column name in brackets, like so: [Create Date]
by Dave Hausler
Useful trick for handling numbers with variable length implied decimal points
by emadns
A basic tutorial for ReportMax tool
by emadns
Using the Chart control in ReportMax
by Peter Piotti
A clean, simple alternative to using the Entity Framework for stored procedures data access in a .NET/SQL Server environment
by S. M. Ahasan Habib
.NET TransactionScope and its default Transaction Isolation level issue.
by Nikita D. Sinelnikov
HowTo: make the report background (elements) of Microsoft .NET Report (.rdlc) non-printable
by zippy1981
This is an alternative for "ODBCTracer"
by Rodrick Kazembe
This is a step by step SQL Server Stored Procedures tutorial for beginners with insert, update, delete and select examples.
by Lee Humphries
LINQ translates .count() to a SQL query that uses COUNT(*), but on large tables even count(*) can be too slow. Here's another way
by basementman
Or, assuming your table has an index, you could do this "old-school" as:select MAX(rows) from sysindexes where id = Object_ID('{tablename}')
by Bryan Kowalchuk
The two most common database lookup table patterns are examined
by shijo joseph
An ADO.NET Layer for SQL Server and Oracle which makes it easier for interfacing with database
by Md. Marufuzzaman
A simple tip/trick to get rows on n’th maximum number from a table
by Md. Marufuzzaman
A simple example of Microsoft SQL Server Pad String
by Marian Placko
This article shows a simple hack of a built-in MS SQL Server WITH ENCRYPTION mechanism
by Chris Maunder
Timing SQL calls with millisecond accuracy
by Rajat-Indiandotnet
A unique feature of SQL SERVER Loop with Go statement
by gunjan k saxena
This tip will help to create an action filter to compress the contents like Json, partial view, etc.
by Jobless Creature
HH:MM Time format addition
by Shahriar Iqbal Chowdhury/Galib
Hi,Here is an alternative for your solutionSELECT CAST(DATEADD(MILLISECOND,SUM(DATEDIFF(MILLISECOND,0,CAST(TMP.TotalTime as DATETIME))),0) as TIME)FROM( SELECT CAST(timeduration AS TIME) TotalTime FROM mytable) TMP
by abdul sami
select aday, code, convert(varchar(5), min(atime), (108))MinTime, convert(varchar(5), max(atime),(108)) MaxTime from testgroup by aday,codeorder by aday asc
by Ankit Bansal MVP
This articles explains the insertion of data into SQL Database using Stored Procedures with Output Parameters. Some Bootstrapping is also used to create a good looking HTML.
by DrABELL
Technique to extend capability of standard SQL by adding the Aggregate Product Function
by Wendelius
Or simply:exec msdb..sp_help_jobsp_help_job (Transact-SQL)[^]
by Elina Blank
When cursors are inside transaction, it is sometimes easy to forget to close the cursor
by Elina Blank
An alternative (simpler way :) ) is:BEGIN TRANDECLARE IdCursor CURSOR FOR SELECT Id FROM MyTable OPEN IdCursor FETCH NEXT FROM IdCursor INTO @CurrentIdWHILE (@@FETCH_STATUS) = 0 BEGIN -- do work IF @@error 0...
by Kabwla.Phone
You also might want to look into the "LOCAL" keyword.This limits the scope of the cursor to the context in which it is created.DECLARE IdCursor CURSOR LOCAL FOR SELECT Id FROM MyTableThis is beneficial for many reasons.
by Elina Blank
To see the default value of the cursor scope:select * from sys.databases(if value of "is_local_cursor_default" is 0 then scope id global, otherwise it is local).The scope is GLOBAL by default (for compatibility reasons).To change default scope use following:ALTER DATABASE...
by Wild-Programmer
Boost application speed and performance
by reshi999
Thanks for that. In MS SQL Server, I use the following technique to avoid full compile:DECLARE @sql VARCHAR(100)DECLARE @pk INTSET @pk = 2SET @sql = 'SELECT id, pcname FROM pod WHERE id = ' + CAST(@pk AS VARCHAR)EXEC (@sql)-- or -- EXEC sp_sqlexec @SQL
by NightWizzard
Convert amounts to their spoken equivalents
by Bert O Neill
AngularJS and Web API Active Directory Security (Authorisation)
by Sadeque Sharif
Another way to solve the issue of “A network-related or instance-specific error occurred while establishing a connection to SQL Server…”
by Manjuke Fernando
How to give db_datareader access to a specific user across all the databases on a particular SQL Server
by Chamila Nishantha
This tip describes how to add a running total column to a result set
by Wendelius
This is an alternative for "Applying Running Total to a Result set"
by Haydn Chapman
A method to update a table column with a random set of specified values
by Divyant Kulshrestha
This tip is useful when we have to move data from Oracle database to SQL Server database or vice-versa using SSIS.
by SatyLepide
By analyzing log-in attempts on SQL server, admins can build the complete picture out of the sequence of events that led to compliance failure or unauthorized access.
by DiponRoy
How to auto increment column options in databases
by Eduardo Yost
Creating a Web User Control containing an AutoCompleteExtender for data through WCF (JSON) allowing to store the entity selected through EntityFramework. Entity object serialization from the server to the client and the client to the server.
by GabrieleTronchin
Automatic creation of non clustered indexes using system SQL entities
by Deepak_Sharma_
This article will show how to create an auto-suggest TextBox that will suggest data from a SQL Server database column.
by OriginalGriff
One of the things that it seems far to hard to find is a reliable way of backing up a database, and restoring it again later. Particularly for development, where the SQL server instance and the database are likely to be on your development machine, and very likely to be damaged by code.
by Ahmed Naqibul Arefin
How to backup and restore SQL Server database schema
by vikas_panchal
If you use SQL Server 2005, then do this:Go to your database and right click on the database name.Go to Task and choose Backup and Enter, your backup is created.Then if you want to restore it:Make a new database and right click.Choose Restore database and choose Backfile.Select...
by Hernán Hegykozi
This tip will show how to perform a backup and restore database from an application in VB.NET 2010.
by Dan Steuer
This article will help manage automatic database purges according to basic Document Management principles.
by NaibedyaKar
How to check the query locking the table and to unlock it
by Mahmud Hasan
Be Very Careful When You Write SQL Trigger
by Drew Rhoades
I can't imagine that a correlated subquery is your best answer here:SELECT name FROM teacher WHERE EXISTS (SELECT 1 FROM student WHERE teacher.teacher_id = student.teacher_id)Instead, how about an INNER JOIN?SELECT DISTINCT teacher.nameFROM teacher INNER JOIN student ...
by Heino Zunzer
The possibility to build stored procedures with table-valued parameters is a great new feature in SQL Server 2008, especially if utilized with the also newly implemented MERGE-command. Alas, there are some restrictions (TVPs have to be bound to a User-defined Table Type, have to be passed as...
by Bhushan Mulmule
This is terribly unorganized document with mix of MVC, Entity Framework, LINQ, HTML 5 and JQuery how tos...
by PIEBALDconsult
Performing a bitwise OR aggregate in SQL Server
by #realJSOP
Using common table expressions to build data from thin air.
by Hiren solanki
Building hirarchy in the sense of hirarchy of manager, employee though both are an employee of an enterprise but both are related or depend on hierarchical level.
by Bhishma Anil Kajaria
Browse and Copy data from your CSV file to SQL directly without any Windows application...
by Prasannakumaran Sarasijanayanan
Load data to temporary table, make any additional update if required, create necessary indices, finally DROP live table and RENAME temporary table to production table.
by Emiliarge
Both MS Access formats (mdb and new - accdb), MSSQL 2008 R2, MSSQL CE, SQLite, MySQL
by Wendelius
This tip describes how to calculate an aggregate for dynamically defined columns using UNPIVOT clause.
by Nirav Prabtani
How to calculate distance between two geolocations or find out distance within a specific radius by SQL Server
by vinothharshad
Use the ON DELETE CASCADE option if you want rows deleted in the child table when corresponding rows are deleted in the parent table.
by Pranay Rana
CASE/WHEN return type
by Morten Nilsen
Unless you are placing this code in a stored procedure, you could just as well do this:SELECT *FROM ( SELECT 'A1' AS String1,'B1' AS String2, GETDATE() AS DateCol UNION ALL SELECT 'A2','B2', GETDATE()) AS dORDER BY And then append the sanitized column name to sort...
by George Tryfonas
A (hopefully) simple way to implement a wildcard selection in combo box filters for Microsoft SQL Reporting Services
by AgarwalPriyanka, ErGauravSharma
Challenges faced in data migration testing
by Hernán Hegykozi
This tip explains how to calculate the Check Digit Vertical (CDV) and Horizontal (CDH) by SQL Server.
by Wendelius
This tip shows how to get rows from a table where a field contains a number that is a power of 2 using LOG function.
by Sunasara Imdadhusen
Clear the transaction Log if you are facing a low disk space
by thatraja
By this way tooHow to Shrink SQL Server database log files?[^]
by sx2008
The root cause why the transaction log file grows so big is the wrong recovery model.The recovery model is set to full by default.99 percent of all SQL Servers never make use of this model because there is no backup of the transaction log file.So the great majority of all databases should...
by Levente Kupás
CLR-addon for T-SQL DATE transformation and Split-String
by Uppuluri Aditya
COALESCE and ISNULL in SQL Server - Part 2
by Homero Ibarra Ramírez
Tool on T-SQL to code basic generator for SQL Server
by Jobless Creature
CTE To find all the related nodes in a hierarcy
by Ravi Tuvar
Concatenate rows with comma separated string in SQL.
by Ramanujam Shankar
Using COALESCE function - concatenate many rows into a single text string output in SQL Server.
by e-Lopes
How to concatenate many rows into a single text string using SQL Server 2008.
by Sanjay K. Gupta
How to concatenate many rows into a single text string using SQL Server 2008
by PIEBALDconsult
See also Stupid CTE tricks -- string concatenation[^]
by Daniel Miller
This tip describes the code to create a custom SQL Server aggregate function that concatenates multiple string values into a single delimited value.
by SergioAmorim
SQL Server and Oracle terms may match, but they can have a very different meaning. This article will help you match one system to the other.
by Masteramuk
JAVA - Connecting to SQL Server database using Windows Authentication or Active Directory
by Bikash Karmokar
Connecting Windows Form Application With ADO.NET in C#
by Kumar Pankaj Verma
How to convert a delimited string in SQL Server to a table column.
by VINEET MISHRA 086
Convert column into rows without using pivot function in SQL
by NightWizzard
Handling for hex expressions and the trailing '}'
by RickZeeland
This console application converts an SQL Server database to PostgreSQL.
by OriginalGriff
If you have an SQL column which contains a comma separated list of names, you may have wondered how to return it as individual rows in a SELECT statement. It's not too bad, really!
by Ashkan.hosseini
Stored procedure that generates insert stored procedure for tables
by Anurag Gandhi
A Query to copy an individual table data between databases
by Antonio Soares
This tip shows three alternatives (an intuitive and less efficient, a more efficient one and a third more efficient one) to count all rows of all tables in a database.
by Mubin M. Shaikh
Create time dimension with 24 hour plus values and time buckets in your data warehouse
by Pascal Ganaye
This SQL stored procedure creates a database from scratch with some meaningful content.
by Rajesh_K_Sharma
How to create CSV file in SQL
by Alexandros Pappas
This tool reads the descriptions of the columns of the SQL server and creates a Word document using SoftArtisans' WordWriter.
by markkang
This tip describes how to generate insert SQL statement from the records in an existing table in SQL server database
by Aadhar Joshi
Creating job in sql server which automates taking backup of all stored procedures and functions in physical drive.
by SuhasHaridas
Create Linq to SQL connection with select, insert, delete, update
by Sandeep Kumar Tripathi
How to create SQL Server Agent Job to schedule SSIS Package
by Roger Wright
A simple example of creating a new database on a SQl Server instance
by Diluka Wittahachchige
Creating SQL Server database project use in Visual Studio 2012 and maintain versions use in TFS
by Ramy Mahrous
IntroductionI got this question from Daniweb C# forum, and of course whenever I need to do something against SQL Server object from .NET I go to SMO (SQL Server Management Objects) which provides a great functionalities to do anything with SQL Server instead of going on SSMS and create some scri
by elizas
SQL Server Management Objects (SMO) are objects designed for programmatic management of Microsoft SQL Server. We can integrate SMO into any .NET based applications.SMO is also compatible with SQL Server version 7.0, SQL Server 2000, and SQL Server 2005, which makes it easy to manage a...
by Indresh_Prajapati
This tip will help beginners to implement CRUD operations in ASP.NET MVC 4 with scripting language as KnockOut and Database as MS SQL 2008R2.
by Indresh_Prajapati
This tip will help beginners to implement CRUD operations in ASP.NET MVC 5 using WebAPI 2 with scripting language as AngularJS and Database as MS SQL 2008R2.
by Prakash Lekhak
Dynamic SQL to get the list Table names
by Akmishra0719
Daily reminder using SQL Agent and SignalR
by Deepak_Sharma_
In this article I will explain how to display data from a SQL Server database table in a WPF DataGrid control
by Bart Ducal
Universal data change tracking solution for auditing SQL Server databases
by Gregory Gadow
Search job commands for text, find jobs by schedule and other spiffy things
by Bertin @nonodata.com
It is often important to have general guidelines when putting together a Data Analysts Team.
by Sumit Garg From Chandigarh
Introduction...
by Jaume González
How to convert any datareader into generic list.
by Sonali Agarwal
There are different types of Database Management System models used for organizing the logical data. Relational model is most popular and widely used model in DBMS.
by cjb110
How to identify the cause of the DataSet Constraint Exception
by Mel Padden
Default keyword in SQL Server
by DiponRoy
Delete all the records from the table using EF
by Arkadeep De
How to remove duplicate records using CTE in SQL
by Manas Bhardwaj
I had these similar databases on my dev environment which I had to delete multiple times during development. As this process was becoming more and more mechnical, I wanted to have a script which would do this for me.
by Darek Danielewski
A small script to remove old user accounts
by Darek Danielewski
This article demonstrates how to safely dequeue items from a shared table
by Venkat Chaitanya Kanumukula
Tableau is one of the powerful reporting tool which is on the market for over a decade. Here's a quick tour in designing BI reports with Tableau using Microsoft Dynamics AX 2012 R3/ Microsoft Dynamics 365 Finance and Operations.
by Robert Lindblom
Detecting concurrency issues when using Entity Framework model first and SQL Server
by GabrieleTronchin
Compare two databases to detect which object has been modified from an old version of the same database.
by Corporal Agarn
Using imported tables that may have a different column name to determine what it is.
by govardhan4u
Determine the datatype of a column in a Excel file in SSIS
by jsd24
The difference between CROSS APPLY and OUTER APPLY of SQL XML
by Basavaraj P Biradar
Difference between SQL Server Char and Varchar data type.
by Wendelius
This tip shows how to calculate a difference between two datetime values and to express the difference in years, days, hours, minutes and so on.
by Yugal Pandya
Display last activity Date and Time smartly like Google and Facebook in Microsoft SQL
by ♥…ЯҠ…♥
Query to check Database, Table, Column exists in Sql Server
by Gaushick
Drop all the tables in a database(give the database name and table name in the below query).
by Matthew Taylor
How to remove Microsoft SQL Server triggers associated with a custom schema.
by Michiel du Toit
Simple SP to drop any general type of SQL Server object
by Jovan Popovic(MSFT)
SQL Server 2016 introduces the new DROP IF EXISTS syntax
by Suvendu Shekhar Giri
Enhancement on dropping an object with check for existence in SQL Server 2016
by Bob Crowley
How to use a CASE statement in ORDER BY to avoid dynamic SQL
by RahulAJoshi
Dynamic paging in grids
by Chetan Naithani
Transforming dynamic row-level data into columns
by Moheeb U.
Here, I have tried to figure out some basic concept about dynamic query.
by ss9o9o9o
Transferring backup files from a remote SQL Server and Dynamic SQL Connection with Restore utility.
by Johnny L Washington
How to execute store SQL with parameters via Procedure
by Kinyanjui Kamau
I have written this tip to help developers automatically set Crystal Report parameters from variables in code (WinForms) at report run time.
by Eligio Morgado H.
Compare two SQL Server databases and show difference in tables and fields
by Herman.Instance
Migrations does not apply to T-SQL rules for ALTER TABLE ALTER COLUMN
by Sarvesh Kushwaha
Binding Gridview (or any other data control) with effective paging using LINQ
by Youqi Ma
Using a controller to manage dynamic control form events and creation.
by Robby Tendean
How to create an efficient paging using SQL script
by NeoPunk
Hi, what about such solution?DECLARE @pageNumber INTDECLARE @rowsOnPage INTSET @rowsOnPage=5SET @pageNumber=2DECLARE @totalItemsToSelect INTSET @totalItemsToSelect=@rowsOnPage * @pageNumberSELECT TOP (@rowsOnPage) * FROM MainTrans WHERE ID IN( SELECT TOP...
by jeantoledo
Take a look at this:DECLARE @ActualRow = 1; /*Start in first item*/DECLARE @ItensCount = 100; /*100 itens for page*/DECLARE @Page = 1; /*Start in first page*/SELECT * FROM(SELECT *, ROWNUMBER() OVER(ORDER BY Name) as ROWNUM FROM Users) as UsWHERE ROWNUM BETWEEN...
by kamiktk123
string Query = string.Format(@"SELECT * FROM (SELECT *, " + @"ROW_NUMBER() OVER(ORDER BY PRODUCT_ID DESC ) AS ROW_NUM FROM({0}) " + @"AS TEMP_INNER) AS TEMP_OUTER WHERE ROW_NUM BETWEEN '{1}' AND " + @"({2} + {3}) - 1", strSql, startRowIndex, startRowIndex, maximumRows);
by kennysun
encrypt all stored procedures in SQL server with powershell
by jroughgarden
This is an alternative for "Encrypting all Stored Procedures of a Database".
by qadirv
Quick C# console application to encrypt all your database stored procedures
by Brady Kelly
A quick and easy way to ensure that your Code First DB Initializer is always run when your app starts, not just on the first data access operation
by Daniel Miller
This tip provides a simple solution to automate the generation of entity and mapping classes for Entity Framework.
by GuyThiebaut
Solving the "Store update, insert, or delete statement affected an unexpected number of rows (0)" response.
by Christopher R Davis
Use model driven development with a MySql backend
by Debopam Pal
How to bring data from Entity model to Excel file using LINQ.
by Michael Haephrati
How to overcome an error message preventing you from saving a change in an SQL Server database
by Nandakishore G N
Example For Gridview RowCommand Event
by IkhwanKrisnadi
How to execute SQL Query / SQL Command on SQL Server using command prompt.
by manish76235
SQLCMD can be used to login to the Sql Server as well. One can only provide Server address, User Name and Password at the command prompt and press enter.The command prompt will change to 1>. Now any sql query can typed and by pressing enter in the next prompt a GO command and pressing enter...
by Sandeep Kumar Tripathi
Here are the different ways to execute an SSIS Package by using C#.
by Muhammad Shahid Farooq
The purpose of this article is to provide a fast but easy way to export data from SQL Server to MS Access.
by Emiliano Musso
A quick method to add days to a date, skipping weekend days if the number of days added results in a Saturday/Sunday
by shijo joseph
A simple and fast CSV reader which you can directly use against Oracle and SQL Server databases or for any direct implementation
by Alexander Konstantinov
Two stored procedures helping developers do less things when they create tables and indeces
by B. Clay Shannon
Create peace and unity in your organization by separating data and coding responsibilites
by Wendelius
Generate Fibonacci numbers using CTE
by R. Giskard Reventlov
When using DateTime with SQL Server, I often forget what the parameters are that allow formatting DateTime in specific ways. When that happens, I fire up this code fragment in SQL Server Management Studio and it neatly lists out every possible parameter with example output.declare @Loop...
by Basavaraj P Biradar
How to find all the Stored Procedures having a given text in it.
by BlackburnKL
We use a slightly modified approach that returns results from more than stored procedures (although it could be modified to return only results for stored procedures). We use this code in a stored procedure that requires a parameter containing the text to search for.@StringToFind...
by Jaume Pascual
SELECT DISTINCT so.name FROM dbo.sysobjects so inner join .dbo.syscomments sc on so.id=sc.id WHERE so.xtype='P' AND sc.text like '%SearchString%'Much faster!
by S.P.Tiwari
Find all the days between two dates using SQL Server
by Sarathi Balakrishnan
Remove duplicate files with same file content, even with different file name using FILETABLE with simple CTE.
by bbirajdar
How to find duplicate values in SQL Server.
by Ramanujam Shankar
Find missing date periods from a table.
by 1Lam
Create the following table on a local database:CREATE TABLE [dbo].[TB_TEMP_TABLESTORE]( [SEARCH_STRING] [nvarchar](128) NULL, [DB_NAME] [nvarchar](128) NULL, [OBJECT_NAME] [nvarchar](128) NULL, [OBJECT_TYPE] [nvarchar](50) NULL) ON [PRIMARY]Rename Yourdatabase to the same...
by NGO Quang Minh
You can create a simple stored procedure like that:DECLARE @StringToSearch varchar(100)SET @StringToSearch = 'GetEmployee'SET @StringToSearch = '%' +@StringToSearch + '%'SELECT Distinct SO.NameFROM sysobjects SO (NOLOCK) INNER JOIN syscomments SC (NOLOCK) on SO.Id = SC.ID AND...
by tarun_j200
SELECT OBJECT_NAME(object_id), definition FROM sys.sql_modules WHERE definition LIKE '%GetEmployee%'
by CaldasGSM
since syscomments is nvarchar(4000) the word may be split into several rows.. so you concat them.. or at least pair them up... here is the sp I use to search on the stored proceduresCREATE PROCEDURE [dbo].[sp_FindInProc] @sText NVARCHAR(MAX) = '%'ASBEGIN SET NOCOUNT ON ...
by ednrg
Not necessarily an alternative, but a wrapper. I created it as a quick stored proc, and put it in the master db, so it can be used in any database.Usage: exec fi 'last_name'.USE [master]GOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE PROCEDURE [dbo].[fi](...
by Pranay Rana
Problem : - During project development I got the requirement that I have to modified the column name of the table which is used in the no of procedure i.e i have to found all procedure related to that table and modify it For the above problem following are the solution that i used First ...
by Nelson Kosta Souto
Find text in Stored Procedures, View, Trigger, and Function.
by Mehdy Moini
How to know which table is updated in the current logfile time.
by Saral S Stalin
Simple query to find the available hard disk space in the server
by Saral S Stalin
The below function will find numbers from a given text in table format.
by André Kraak
This is an alternative for "Finding numbers from a text in SQL Server."
by Wendelius
This tip describes how to fetch the first or the last occurrence of given day of week within a month by using a single SQL statement.
by Zhuyun Dai
Fix multiple SQL Server DTC errors when we use distributed transactions between VMs duplicated from the same template on Hyper-V
by Muhammad Aqib Shehzad
Forgot Password and Email Check from Database
by Ani_0707
This article intends to describe a simple and elegant way of converting local datetime to UTC and store it in DB.
by Michael Selector
A code to declare a table variable which will be populated from a query
by Md. Marufuzzaman
Generate auto row number for a table
by Mukund Thakker
SELECT ROW_NUMBER() OVER(ORDER BY [col_1]) as RowNumber,COUNT([col_1]) OVER () AS RecordCount,* FROM TableName
by YSLGuru
If you have the ability to change it, you may want to consider moving away from the 36 digit alphanumeric created by GUID() as a Key. This is often misused in SQL-Server by developers who have not had proper training/education in SQL Server and or RDBMS. The GUID() is not intended to be a...
by Pavan Thakur
I had a requirement to create automatic date entries into Scheduler SQL table. Whenever a Schedule with RecurrenceRange was set with 'No EndDate', the dates will automatically get added from backend for next year through a job.
by Johirul Islam Tarun
Easily find table description.
by Rishikesh_Singh
Generate Insert script to extract data
by Sunasara Imdadhusen
SQL Server 2005 : Generate Script with Data from Database – Database Publishing Wizard
by tarun_j200
SSMS also provides the option to generate SQL script file which contains both schema and data.Right click the database and select Generate Scripts under Tasks Menu.Click Set Scripting Options on the left hand menu (in SQL Server 2008 R2) then click Advanced button, there is an option under...
by Md._Mehedi_Hasan
This tip will help you to generate .xml file in AngularJs and ASP.NET MVC5 using XElement of C#.
by Harsh Gandhi
Generate XML Using FOR XML ; Difference between different modes (AUTO, RAW, PATH, EXPLICIT) of FOR XML to generate XML in SQL Server
by Wendelius
Generate a set of random numbers by using CTE
by Tharaka MTR
This article describes the easiest way to create and process delimited row using SQL XQuery.
by HHerzl
HowTo for generating a data dictionary from existing database
by Wendelius
How to generate desired amount of rows in SQL Server using CTE
by Sergii Syrovatchenko
This tip describes the most convenient way of process automation of generating HTML reports for dynamic table-structures and sending them to different people.
by Purushotham Agaraharam
Creating a parameterised report using SSRS.
by Shamas Imran, Muhammad N@beel
Convert Coordinate data to strings to be stored in database.
by Md. Marufuzzaman
Get accurate age by date using MS SQL Server
by Trung Nguyen Son
How to analyse and tune your dotnetnuke site to get best performance.
by rajivlipu
select days_of_month=day(dateadd(mm,-1,'12-feb-2010'),-1) :laugh:
by g_p_l
@dt is a datetime valuederive the first of this month, add a month to itthen subtract 1 day to get the last day of this monthselect days_of_month=day( dateadd(d,-1, dateadd(m,1, dateadd(d,1-day(@dt), @dt) ) ) )
by Md. Marufuzzaman
This is a very simple use of SQL Server global variables. Microsoft SQL Server provides a massive number of global variables, which are very effective to use in our regular Transact-SQL. Global variables represent a special type of variable. The server always maintain the values of these...
by Srinubabu Ravilla
How to get SQL Server database connection string easily from Visual Studio
by Dave Elliott
Global Stored Procedure to retrieve tabular information or a CSV list of columns for a database table.
by Arslan Elahi
Get the Comma Separated Value of one or multiple columns from SQL table
by Dhol Gaurav
Get Tables List With Its Dependent Tables Names
by shivaramakrishnaReddy
Get time difference in the format "HH:MM:SS" for two different DateTime values in SQL Server.
by Mahmud Hasan
How to use variable in SELECT TOP SQL command
by PIEBALDconsult
Using a Common Table Expression to produce a list of Views, Procedures, and Functions
by PIEBALDconsult
How to get a list of SQL Server modules to refresh
by Mahmudul Haque Azad
Getting all table and schema names containing particular column name
by vikram.mahapatra
How to get the current time from any time zone
by Basavaraj P Biradar
GO Statement can also be used to execute batch of T-SQL statement multiple times
by Robert Bettinelli
Check this for a good universal way of running stored procedures..
by RahulAJoshi
Grouping dynamically on different columns in single query
by Omar Frometa
Grouping Sets is the new SQL Server 2008 Operator
by db_developer
There is no way to show hierarchy level in one dimension of one cube and to hide that hierarchy level in the same dimension (role-played dimension) of the same or other cube. Solution is to add additional hierarchy without levels to hide to this dimension.For example,There is dimension...
by Igor Krupitsky
Fast function that excludes weekends and holidays
by Sudheer Reddy Battula
Add an identity column to a table with data
by cattman1970
Function that consumes a Columbia Gas account number of 11+ digits and returns the check digit
by Syed Moula Ali
How to compare database schema in VS 2012 and how to update the target database to the server
by kasiarun
How to connect to Analysis Services (SSAS) from a different domain user
by RaviRanjanKr
This tip enables you to convert nvarchar, money and smallmoney values to int.
by Panayotis Matsinopoulos
Store your date time values in UTC format and convert it to local time when you present it to the user.
by Tom Clement
I wanted to point out that while I agree with the general approach (storing DateTime in UTC and converting into local time for display as well as accepting input in local time), it's not always what the requirements call for. If you're creating a meeting calendar, then of course it's perfect,...
by Philippe Mori
In my opinion, Local to UTC time conversion should be done nearer to UI level. That is, you should pass UTC time to your query and the time should be converted later when it is displayed to the user.Doing the conversion in code will simplify SQL queries and thus probably improve overall...
by Sudheer Reddy Battula
Copy a SQL Server table
by Daniel Miller
This code snippet shows how to count all the tables and rows in a SQL Server database
by E. Scott McFadden
This article explains how to create and use a self referencing key in a SQL Server Table.
by Ramy Mahrous
Well... we need to assign a server login to has access on a database, let's say the SQL Server Login we had created programmatically should has access on database "Database1" and for some reasons we should do that programmatically Well. Create any C# project type (Windows, Class Library or even Cons
by kiran dangar
Understrading sys.objectsSys.objects is a system VIEW in SQL Server 2005, for each SQL database there is a separate sys.object view which gets stored within databse itself.Using Sys.objects returns list of all database objects and its types, type can be either of given below:DB OBJECT...
by VDmitrovsky
1) You cann't drop any object in schemas other than dbo, so you MUST use sys.schemas system view properly.2) You cann't drop tables even in dbo schema if they are referenced by other ones, not dropped so far. Drop all FKs before tables.dva
by kiran dangar
For Ravi LVS,The way you have suggested to Empty the database by just deleting and recreating it, is not at all smarter way when you are about to empty a remote database located on live database server, There are times when you don't hold such rights of deleting database on Live...
by Maciej Los
This tip is desired for those who want to list all available SQl Server instances that are in a network.
by Wendelius
Few tips for connecting to an SQL Server instance using DAC
by S. M. Ahasan Habib
I will explain very simple way to execute multiple script files (*.sql) from a directory.
by Wendelius
This tip demonstrates the use of LAG and LEAD functions in SQL Server.
by Ameet Parse
This article describes How to find a Text in Stored Procedure (Checked on SQL Server 2008)
by Ameet Parse
This is an alternative for "Find all Stored Procedures having a given text in it"
by Rajat-Indiandotnet
Find column or Text in entire stored procedure
by Ed Nutting
How to fix LocalDB / SQL Server: "Cannot open database "XYZ" requested by the login. The login failed. Login failed for user ABC"
by Wendelius
A little tip on how to format repeating values in SQL output using LAG function
by Sergii Syrovatchenko
T-SQL code generation by using Dynamic SQL for routine tasks automation.
by nit_singh
A method of comparing with an empty GUID
by Wendelius
This tip describes how to guarantee a fixed amount of rows in a table by using triggers
by ChienVH
This article will show you how to implement Asp.Net membership into a new database
by Amit Singh Baghel
Saving Details Table Data (An HTML Table) in Database by converting it into a jagged array and passing it to a table type parameter
by NightWizzard
Read and/or modify database objects like views, triggers, stored procedures and functions from .NET code.
by Kale Yogesh
How to Partition Table in SQL
by Karsten Krug
A workaround for reporting services' missing ability to customize report parameter placement.
by Shao Voon Wong
How to prevent SQL injection attacks when using dynamic SQL in stored procedures
by chetan dudhagara
How to Protect from SQL Injection in PhP based website
by Wendelius
This tip describes how to delete duplicate rows from a table that doesn't have a key.
by Costica U
Here is another solution:IF OBJECT_ID( 'tempdb..#TestTable' ) IS NOT NULL BEGIN DROP TABLE #TestTable ENDCREATE TABLE #TestTable ( Column1 varchar(1), Column2 int )INSERT INTO #TestTable VALUES ('A', 1);INSERT INTO #TestTable VALUES ('A', 1); --...
by Wendelius
This tip describes how to delete duplicate rows from a table that doesn't have a key.
by Ron sikander
Find out the number of duplicates in the table:select count(*), VISTX_ST_FIPS,VISTX_CTY_FIPS,VISTX_TC from TR00.NV_STARTER_INDEXgroup by VISTX_ST_FIPS,VISTX_CTY_FIPS,VISTX_TC having count(*)>1--- Delele them using following statementDELETEFROM TR00.NV_STARTER_INDEXWHERE...
by Tejas Vaishnav
Resetting an identity column in SQL Server
by yash soman
The error occurs when we try to create a new Microsoft SQL Server Database File (SqlClient) using Visual Studio IDE
by Bhushan W. Juare
The different ways of retrieving XML data from SQL Server.
by B. Clay Shannon
Save Excel (or other types of) files to SQL Server, then read them out again and make them downloadable via a link on an ASP.NET Web API page
by Sandesh M Patil
How to search a column name within all tables of a database and how to search stored procedures containing a particular text
by SA - Hibbert
Return all records between two dates that include time in SQL.
by Abhishek Sur
It is a common issue of many of the guys on how we can fetch a record based on its record number. It is really easy to get first 10 records usingSELECT TOP 10 * FROM EMPBut when we want to fetch records in such a way say I need to fetch record from 40 to 50. This comes very handy when...
by Wonde Tadesse
This tip/trick helps to set a default value for blob data type such as Image, VarBinary.
by Rohan Kishor Garud
RoundhousE (RH) is a database migrations engine that uses plain old SQL Scripts to transition a database from one version to another.
by Md. Marufuzzaman
This tip shows you an easy way to split Microsoft SQL Server table row data.
by P_Dash
Taking a SQL Azure database backup to Local instance from an SQL Azure instance using Deployment Technique
by BillyGoatGruff
SQL Profiler is not included with SQL Express, this tip will help if you need to track client activity.
by Kumar Pankaj Verma
Truncating log file in SQL Server using T-SQL when log file is too large and database becomes unresponsive.
by ManojKumar19
Update row column with another row column in same table SQL only if it is null.
by OriginalGriff
How do you call a Stored Procedure inside a query and use the SELECT results? Tricky...or is it?
by MAW74656
This is a drop-in solution that mimicks the functionality of xp_sendmail (including query results), without installing Outlook on the server.
by mgoad99
Using winSCP to download a file through SFTP within an SSIS package
by Bhushan W. Juare
This tip shows how to use SQLCMD utility in SQL Server 2008.
by Bojjaiah
Single Stored Procedure for delete/retrieve all table of records
by Md. Marufuzzaman
I don’t know why my boss always gets angry when I alter Microsoft SQL Server database objects such as storedProcedure, functions, views, etc.
by jwood_denver
Why don't you just use a query like this?SELECT CAST(serverproperty(N'servername') AS varchar(50)) AS [Server Name], db_name() AS [Database Name], SCHEMA_NAME(schema_id) AS [Schema Name], [name] AS [Object Name], [type_desc] AS [Object Type], [create_date] AS [Create...
by Aqeeel
Identifying and deleting duplicate records from SQL Server Table
by Uladzislau Baryshchyk
In this article, I'll show you how easy it is to move your MS SQL database to Amazon RDS cloud
by Arvind Singh Baghel
Import CSV or txt File Into SQL Server Using Bulk Insert.
by Satya Karki
How to import or restore BACPAC file using SSMS
by Satnam Singh CapGemini
Improving backup performance
by Mr. Joydeep Das
What the effects of Ordering in Index
by RickZeeland
Inno Setup script to install SQL Server 2008 R2 with Tools, creating an instance with special rights and displaying the log.
by Mehul M Thakkar
I was facing the problem of inserting a default value on single column table and I have achieved via this way.insert into > default valuesAlso this could be used for many columns in a table defining with default constraints.ThanksMehul Thakkar
by mravikiran
INSERT with SELECT vs INSERT with VALUES
by Andrew Rissing
You might want to do some further testing... It seems if you perform the following, the values are actually the same:SET NOCOUNT ONDECLARE @TMP TABLE( EmpName VARCHAR(50), Age INT)PRINT CONVERT(VARCHAR, GETDATE(), 121)INSERT INTO @TMP(EmpName, Age)SELECT 'Ravi Kiran',...
by Praveen Meghwal
How we can write a single statement to perform insert, update and delete operation
by Nabil Droussi
This article will walk you with steps on how to install, configure and connect to SQL Server 15.x on,Linux Ubuntu Server 18.04 LTS
by Ravi Tuvar
Installing SQL Server 2005 and 2008 in the same computer.
by Sarkis Matossian
The steps to install a CLR Stored Procedure in SQL Server
by h_wiedey
Usage of instead of triggers in Object-Relational (O/R) Mapping
by Sandeep Singh Shekhawat
How to get the last inserted identity value of an auto increment column of database tables using SQL Server variable (@@IDENITY) and functions (SCOPE_IDENTITY() and IDENT_CURRENT())
by Mubin M. Shaikh
Create Virtual Column Using Named Calculation in SQL Server Analysis Services
by Mubin M. Shaikh
Create Named Query in Data Source View While Designing OLAP Cube in SSAS
by Herman.Instance
When using SqlDependency, is it possible that a detected change leads to 0 rows in the SqlDependency results?
by Satnam Singh CapGemini
Cannot Bulk Load Data Into the Table with Primary Key Constraint on it
by wizardzz
I would definitely include some security measures in here as they can compromise the data being stored. Though the system may remain up after a breach, it will be too late to prevent damage once it's done:16. By all means necessary, take measures against SQL injections. This is probably a...
by __Untitled
Actually, we think xp_cmdshell is not safe enough, and need to be enabled using surface area configuration explicitly (SQL 2005). We use xp_delete_file instead, sample code:DECLARE @l_Runtime DATETIME, @l_BackupFileName VARCHAR(256), @l_FileExists INTSET...
by Mohammed Nazer
SQL Constrains details and its types
by Pareek Ankit
Leveraging SQL-Server - Custom rule engine
by AspDotNetDev
This query will show you all tables and columns in a database, and it can be pasted into Excel for easy manipulation.
by Chris Maunder
A quick script to enable you to find the processes that are blocking in SQL server
by Chris Maunder
Here's an alternate version that doesn't use sp_who yet provides a little more information. It also provides the option to kill the blocking processes themself.IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ListBlocking]') AND type in (N'P', N'PC'))EXEC...
by Hussain Patel
Display the list of all Tables, the Referenced columns, the Referencing Table, the Referencing columns and the Constraint name in a database
by Chamila Nishantha
Simple query to get table column name as rows
by PIEBALDconsult
This is an alternative for "List SQL Server table column name as rows"
by Wendelius
This is an alternative for "List SQL Server table column name as rows".
by Manikandan Sekar
Loading Data from Excel
by Federico Colombo
How to replace textual properties of EF Objects with translations
by pankajupadhyay29
Use this when you want to perform a task on all tables in a database
by Member 10510822
LPAD and RPAD function works for padding in SQL Server
by PIEBALDconsult
This is an alternative for "LPAD and RPAD functions in SQL"
by PratapReddyP
Merge in SQL Server 2008.
by Marc Leger
ORM, databinding, asynchronous data access, and transactions
by Marc Leger
Microsoft ASP.NET Identity MerlinFramework
by DataBytzAI
How to refresh intellisense after adding new objects in Microsoft SQL Management Studio
by Paw Jershauge
MS SQL system views, mapped over version.
by Atul_Kapoor
SQL Server Reporting database migration from SQL Server 2005 to SQL Server 2008 R2
by Mike Winiberg
GOTCHAs and tips useful when migrating a complex Access JET application to SQL Server 2012
by Member 7874525
This how you can monitor your database changes
by Telegram:@ArastoAhmadi
Tutorial to monitor database changes without using tools and by using a simpler trick
by MarcusCole6833
Make some SQL XML dot style another way
by User-12551084
Moving database file from one drive to another drive
by Dinesh K.S. Kushwaha
Tip on CROSS APPLY and OUTER APPLY
by OriginalGriff
Inserting a number of rows in a database isn't difficult, but how do you do it in a single command without concatenating strings?
by Paw Jershauge
Want your own movie database??? Download IMDB in 20 minutes.
by Oscar Arros González
A solution for the name resolving problem with DTC.
by yuanfeng.ma
New high-availability/disaster-recovery solution provided by SQL Server 2012.
by A.Ebrahimi
Connect to local database on MS SQL Server in local machine and develop node.js code
by thatraja
SELECT TOP 1 salaryFROM (SELECT DISTINCT TOP n salaryFROM employeeORDER BY salary DESC) aORDER BY salarywhere n > 1SQL SERVER – Find Nth Highest Salary of Employee – Query to Retrieve the Nth Maximum value[^]
by Costica U
The original solution has some issues. Check the following script:IF OBJECT_ID('tempdb..#salary') IS NOT NULL BEGIN DROP TABLE #salary ENDCREATE TABLE #salary ( Salary INT )INSERT INTO #salary(Salary) VALUES(5) -- 1INSERT INTO #salary(Salary)...
by Pranay Rana
Getting a SQL Server RowCount Without doing a Table Scan
by Durgesh Swarnkar
Getting the count of records in a particular column.
by SERokon
OLAP cube performance optimization technique
by RaviRanjanKr
A tip enable you to learn how to use Column_Index instead of Column Name with Order by clause
by John Bhatt
The most versatile control of ASP.NET, DataList, lacks one thing Pagination, built in.
by zvin
Passing a datatable to a Stored Procedure in SQL Server 2008 which helps improve performance.
by OriginalGriff
If you try to pass a DbNull.Value to an SQL Image column, you get an exception: "Operand type clash: nvarchar is incompatible with image" - not sure why it's throwing that, but it can be done.
by Darek Danielewski
The importance of using parameterized SQL queries has been well established, but passing table values or occassional NULL values has always been a problem ... until now ...
by Tom Glick Philadelphia, US
POC to demonstrate passing of collections of complex objects to ASP.NET Web API Controllers.
by RedDk
Use ALT+SHIFT to "block" select text (thinking of justifying columnar relations of words/data/etc. so the visual appearance is perfectly tabular) ... and TAB (TAB+SHIFT to undo) to MOVE SELECTION right (and left) ...
by #realJSOP
It doesn't always happen the way you expect.
by C Is Sharp
PHP and Accessing MS SQL Server in Unix/Linux.
by Micah Ebohon
Having MSQL and ODBC connection string in one configuration file for your application
by Sifiso W Ndlovu
This tip illustrates a workaround to SQL Server pivoting on variable character data types.
by Reader Man San
Plug-in Architecture To Work in WinForms MVC + WPF MVVM + ASP.NET MVC + Mobile (Xamarin MVC/PhoneGap MVC) + Win 10 Universal App MVC
by Trond Lind
Prevent brute-force login attacks on a remotely accessible SQL Server database using T-SQL
by Nagaraj Muthuchamy
This article gives an introduction on SQL Injection attacks and tips to prevent it.
by Sameh Abdel Mongy
Deploy Reports rdl files to SSRS using C# script
by Federico Di Marco
Query Excel or CSV files with T-SQL without importing them in a table first
by Mukit, Ataul
Calculate running total or cumulative sum from a table in a SQL Server database.
by Elina Blank
Using window functions (partition by) will speed up the process:SELECT Val, SUM(Val) OVER (Partition BY [YourPartitionValue] Order BY [OrderColumn] as CumulativeSumFROM [Table]
by iamalik
I guess this is more faster:SELECT T1.Field1, SUM(T2.Field1) FROM [Table] T1, [Table] T2WHERE T1.Field1 >= T2.Field1GROUP BY T1.Field1
by S Douglas
Another way of getting totals, whether it be by group or set is to use the CUBE and ROLLUP predicates.By group (each grouping of FIELD_DESCRIPTION will have a total sum):SELECT FIELD_DESCRIPTION , SUM(FIELD_VALUE)FROM tbl_DataGROUP BY FIELD_DESCRIPTIONWITH CUBEOr:By Cube...
by fordc03
This will work on SQL 2000/2005/2008.Most cumulative aggregations have constraints such as a begin and end date or grouped by customers.Your solution is good for a single aggregation without much filtering. People will find that the query plans generated would be very similiar to that of...
by Dave Elliott
Find the column information of a SQL query
by groggyjava
SQL 2012 Code Snippet for quick blank transaction
by Subha.N
Tip to create a database application using C# .NET in the shortest time possible.
by Gene R. Browning
Generate random dates (and times if you like) for your test data environment.
by gayani dassa
Read & Insert Data Using Stored Procedures
by Md. Marufuzzaman
How easy to read a file without using of the seven extended stored procedures.
by pankaj_254768
Shows how to read an Excel file using SQL query commands from SQL Server
by Christian Del Bianco
In this simple example, we are going to see how to update an HTML page when a SQL Server table change occurs, without the need to reload the page or make asynchronous calls from the client to the server.
by thatraja
The below query can be used to get the record count of all tables in the current database.
by Md. Marufuzzaman
This is good... You can also consider this link.[^]
by tarun_j200
Also use either this one:SELECT OBJECT_NAME(SYSINDEXES.id), SYSINDEXES.rowcntFROM SYSINDEXES INNER JOIN SYSOBJECTS ON SYSINDEXES.id = SYSOBJECTS.idWHERE SYSINDEXES.indid < 2 AND SYSOBJECTS.xtype = 'U'or this one:SELECT OBJECT_NAME(id),rowcnt FROM SYSINDEXES WHERE...
by Pranay Rana
Number of different ways to get total number of rows from tables
by Graham Cottle
Sometimes it is necessary to have the schema name included as well. I concatenate with the table name for my convenience, but it is not vital to do so.SELECT sys.sysindexes.rows, sys.schemas.name + '.' + sys.objects.nameFROM sys.objectsINNER JOIN sys.schemasON ...
by Member 3128846
Example to implement remoting concept using SQL Server database
by GabrieleTronchin
A simple stored procedure to add at your database to keep it reactive
by Pavel Sinkevich
If data source is populated manually, there is a typical problem: a mix of visually similar Cyrillic and Latin letters. This tip describes how to fix it.
by Mycroft Holmes
When grouping data within a List control I need a header table and child table. The data comes from 1 datatable where the 1st #n columns are duplicated for each detail rows.The usual answer to this is to set the hide duplicates value in the textbox. This suppresses the text but the row is...
by Yogesh Gulve
Return Comma Separated String using SQL
by SonuKSingh
rowversion datatype in SQL Server: Track which row has been modified
by Mubin M. Shaikh
Manually Run SSRS Scheduled Reports
by Ahmet AYDIN
This post describes step by step how to run a Single Page Application template using ASP.NET Web API 2 and angularJS and how to use Web Application Project whose name is Dalyan.
by Jason Parms
Lightweight Directory Access Protocol (LDAP) Injection
by IkhwanKrisnadi
How to solve when saving changes is not permitted on SQL Server 2008 Management Studio
by hmdmgd3
SQL code allows you to find objects using multiple keywords in your DB
by Saral S Stalin
You can search for any string with in the TSQL scripts of all the Stored Procedures in a database using the syscomments table.
by DiponRoy
Select a default row for a query that returns no rows
by sachin bankar
How to use the result set from a Stored Procedure in a Select statement.
by Luca Astolfi
User defined procedure for make an HTML table from T-SQL Select statment
by Wendelius
This tip demonstrates how to select valid records from a table that contains validity date limits.
by Jobless Creature
Masking selected characters in SQL, hiding few characters
by mparvez
Session killing from a SQL Server database.
by piyush_singh
This article will help us in setting the format of date values coming from a database.
by Saral S Stalin
Explains how to run a script with higher priority to avoid it getting terminated in a deadlock situation.
by DecodedSolutions.co.uk
This is a simple article describing how to create an add an outlook appointment to your MS Outlook Calender.
by headshot9x
How to create ShoppingCart using Gridview in asp.net with code VB
by Mehdy Moini
Implementing a map as a tree, and finding the shortest path, between the streets, is what you will see.
by Kale Yogesh
SHRINKFILE and TRUNCATE Log File in SQL Server 2008
by Mike Trank
Simple Daily SQL Server Database Backup Batch File
by OriginalGriff
Did you know that Windows provides a built in way to build SQL connection strings for you? Neither did I ... until I found UDL files.
by Ajit Kumar Thakur Microsoft
This tip contains simple step by step solution to read SSAS cube data using MDX query and display in SSRS report.
by SERokon
Exclude Column from SELECT * statement
by bmckuhen
How to get a quick list of all DBs using SMO
by Tigya
Snippet and Surround features in SQL Server 2012.
by rnbergren
Gives a run down of how to sort parameters for sharepoint lists selections
by Itai Basel
Finally found a solution to the annoying LINQ to SQL dbml error: CS0029 : Cannot implicitly convert type 'int' to 'System.Data.Linq.Link'.
by Mani Bhushan
Some Important SQL Queries
by jim lahey
As a C# developer, I much prefer to perform this kind of task with SMO. The API is really nicely structured and gives quick, strongly-typed access to the nuts and bolts of SQL Server.Using SQL 2008 and Visual Studio 2010, you need to add the following references from C:\Program...
by Anurag Gandhi
I have gone through a lot of examples to sort alpha numeric data in sql. Here is my way:
by PIEBALDconsult
Interspersing 'Total' rows among summarized data rows in the correct order
by bbirajdar
Use of soundex() function in SQL server
by Paw Jershauge
An easy to use extendedproperty procedure (alternative to sp_dropextendedproperty, sp_addextendedproperty, sp_updateextendedproperty)
by DiponRoy
Split date time ranges into days or possibly other ranges using CTE in SQL Server
by db_developer
Split User Defined Function, MS SQL Server 2008
by Gauri Chodanker
SQL function in SQL
by Glagace_7763
Create a table from a Varchar list value
by Robby Tendean
How to do SQL atomic operations on UPDATE and DELETE syntax.
by Rajesh Manjarekar
When CDC is turned ON against a table and the underlying table schema changes, such as adding/removing a column, changing datatype etc
by Rajesh Anuhya
It help's to verify if the card number provided by the user is valid or not.
by Pranay Rana
How to use Group By clause when joining to table Let's consider one scenario where I have two table employees (contains employee detail) and sales (contains infomation about sales done by employee).Structure of...
by Guni Van
Mapping your database with C# object class, then make typed-safe query like SQL syntax
by Mr.Thursday
SQL script for creating ASP.Net Identity Database
by Nitinpatel
This SQL script will generate a script to drop and create all foreign keys in database.
by mkader
SQL scripts to insert File to BLOB field and export BLOB to File
by Vivek Johari
Nice tip Kanasz :) You can also create the linkedserver through SQL SERVER MANAGEMENT STUDIO by following the following pathClick on the Server ObjectsRight click on the Linked servers under the Server Objects and select the New linked Server option.
by aasim abdullah
Backup and then restore of a database is a normal job for developers and DBAs. This script will be helpfull to findout, from which path, and which backup file a database was restored.
by Prasad CM
How to fix this error.
by Krishna KV
Dynamic masking using SQL Server 2016
by deepakaitr12345
How to create an assembly in SQL Server and store it in the database.
by Charles T. Blankenship
Backup and Restore SQL Server utility (where there is no SMSS onsite)
by Chris Winkelmann
Display a SQL Connection Dialog with extensible functionality to persist the resulting connection string to any location...
by Dathuraj Pasarge
Know whether your databases are backed up successfully in the last 24 hours or not !!!
by Atul_Kapoor
Perform SQL Server Instance health check simultaneously on more than one server using Powershell
by Hernán Hegykozi
Marks a statement block as a critical section by obtaining the mutual-exclusion lock
by Dimitri Witkowski
Recently I had a problem: I was developing a logon trigger for SQL Server, and there was a bug in it. After deploying the trigger to the server he didn't allow me to login anymore. I was in panic and thought I would have to reinstall SQL Server.Fortunately, I've found a solution how to...
by aasim abdullah
Using SQL Server Management Studio, have you ever come a cross following questions: Why every time, a new query window is open with MASTER database.? On opening SQL Server Management Studio, I need a new query window automatically ?
by Atul_Kapoor
Steps for deploying Restart Health Check script in a SQL Server environment.
by aasim abdullah
A stored procedure can be called from another stored procedure as nested stored procedure. How to get a list of these stored procedures with their nested one
by Surender Singh (CodeToastDev)
Custom StringPadding functions for SQL Server
by Sivaraman Dhamodharan
How do you use the Template explorer and assign parameter values.
by Michael Ecklin
This tip describes Microsoft SQL Server implementation of XIRR function.
by aasim abdullah
Automatic query execution at every instance startup.
by aasim abdullah
You have place indexes but still queries are slow... are you facing bookmark lookup problem ???
by DiponRoy
Using CASE with variable/SET, SELECT/UPDATE statement, WHERE clause, JOIN & ON clause
by aasim abdullah
How to use DELETED and INSERTED virtual tables to capture data change in result of any INSERT, UPDATE or DELETE statement.
by DiponRoy
How to do string split and join in SQL Server
by DiponRoy
A utility query to find table generations in SQL Server relational database
by DiponRoy
Finding week start and end date time from a given date time
by aasim abdullah
A simple query to get all databases size on a given instance.
by aasim abdullah
Get all indexes list in detail, with their involved columns
by aasim abdullah
How to Refresh Intellisense Cache in SQL Server
by aasim abdullah
How do you know, if someone disabled your job at production database server. Who is the calprit. How to send a mail alert for this change ??
by aasim abdullah
Restore failure from Enterprise to Standard edition in SQL Server.
by prashant0556.s.more
The script helps to find out upcoming birthdays even when days cross a year.
by aasim abdullah
The TOP clause is commonly used to get the top required rows from a result set. The beauty of this clause is that it can be used with the WITH TIES clause to retrieve all similar rows to a base result set.
by Claudio cespon
A first approach to avoid Dynamic SQL in stored procedures
by Brad Joss
SQL CLR Functions for Zip Compression and Regular Expression evaluations
by Srinivas Kalabarigi
Column values as comma separated string in SQL
by Jan Steyn
How to resolve this.
by Peter BCKR
a simple way to estimate as accurately as possible route-distances and traveling times without exact route calculation in sql
by Prasanta_Prince
Sqlserver Trigger
by SalizarMarxx
This article demonstrates the #1 failure when people write triggers.When writing SQL triggers you can NEVER be sure that you will ONLY have one record when processing the trigger results.In Your example only the first record from the INSERTED table will be captured, or worse random bits...
by DiponRoy
A utility class to send parameters for IN() operator in SQL using parameterized queries
by Rajesh Manjarekar
I found out that a possible cause is the difference between the SSIS 32 bits and 64 bits environment
by Ramy Mahrous
hmmm, nice we have SSIS it makes life easier but it usually comes with non-understood problems like "SQL Server Destination" (2185) failed with error code 0xC0202071 it means when you insert data into table in remote SQL Server don't use SQL Server Destination component however use OLE DB Destinatio
by Rajesh Manjarekar
How do I set FileSpec dynamically for looping files in a foreach loop container?
by mparvez
How to load data from an Excel file to load in a dimension table in an incremental way.
by mparvez
Load data in Dimension Table using SQL.
by mparvez
How to normalize a table by using lookup transformation.
by mparvez
Transform data by using regex and Script Component.
by mparvez
SSIS fuzzy lookup for cleaning dirty data.
by Chirag Vidani
How to hide PDF Export option in Report Viewer
by Jesus Carroll
This brief article show how to install quickly Microsoft SQL Server 2008 Express Edition Standard or with Advanced Services
by jstntham
Utility to auto generate individual Stored Procedure classes corresponding to each Stored Procedure on a Microsoft SQL Server database.
by Mahesh Bailwal
This is a stored procedure generator for SQL Server
by Anton Burtsev
Performing fast concatenation of strings from different records
by AspDotNetDev
I like the original solution, especially when compared to this (which I am posting just to show that there are other solutions):-- Initialize table.CREATE TABLE #BigStrings( StringID bigint IDENTITY(1,1) NOT NULL, StringValue text NOT NULL, CONSTRAINT PK_BigStrings PRIMARY KEY...
by smirson
This is an alternative for "String splitting/tokenizing using T-SQL user defined function."
by Irfan Baig
String splitting/tokenizing using T-SQL user defined function.
by Hajo Messner
There is a little inconsistence in this function, because the @Tokens Elements and the @Delimiter parameter are of data type NVARCHAR (=Unicode) while the @String parameter is of data type VARCHAR (=ANSI). If the @String parameter can be Unicode, it must be declared as NVARCHAR. If the @String...
by PIEBALDconsult
Concatenating values from multiple rows into one string value via a Common Table Expression
by Jörgen Andersson
Pretty cool little trick you've made there.With the help of an analytic function, I've fixed the ordering, and as a byproduct it also scales better:WITH ranked AS ( SELECT make,model,Rank() over (PARTITION BY make ORDER BY model) Rnk FROM MakeModel ),cte...
by Vinay Haravi
Term Lookup is the one of the powerful Transformations in SQL Server Integration Service. This transformation basically helps to analyze the set of text records.
by BharatRamV
Finds the Best Table for a given set of columns
by Arif H Shigri
This tip will discuss the difference between ROW_NUMBER(), RANK() and DENSE_RANK().
by #realJSOP
When all else fails, fire off some events and bask in the glow of the IDE's Progress tab.
by Pascal Ganaye
Reproducing the SQL RAND() function in C#
by Rion Williams
A one-stop-shop for improving the web.
by Jatinath
This tip will help you to find a particular text used in SPs, Functions or tables
by Jaime Olivares
How to Insert or Update an SqlGeography object in SQL Server 2008 from a C# application
by Brian C Hart
Provides the quick-and-dirty syntax to connect to a given Microsoft SQL Server instance so you can then run a .sql query script against it, e.g., if you are calling this from code as part of a larger pipeline
by Wendelius
The tip shows how to intentionally cause an error in a situation where a non-existing reference would be updated.
by Gaushick
To find duplicate rows in table
by Member 7759061
Here is an alternative way to find duplicates in a table by making use of over clause http://msdn.microsoft.com/en-us/library/ms189461.aspx[^];with duplicates as (SELECT rowno=row_number() over (partition by colname order by colname), colname, colname from TableName)select * from...
by santosh poojari
To remove or replace multiple special character from string using sql queries.
by Syed Moula Ali
Replicate/Clone/Duplicate selected data in a Table using merge statment
by Talking Dotnet
The SELECT TOP N query always returns exactly N records, and randomly drops any record that have the same value as the last record in the group.SELECT TOP 5 price, Booktitle FROM BookTitles ORDER BY price DESCThis query will give 5 records from table BookTitles in descending order by price. ProblemS
by Tamer J. Mehyar
A simple way to keep track of DB objects versions (DDL updates) in SQL Server
by zvin
When comparing data stored in databases, you don't need to use RTRIM()
by Emad Sammour
Mapping table is used in the translation - output in Unicode (nvarchar)
by Abdul Quader Mamun
To traverse a table without cursor, you only need to add an additional field in the table with null value. Here is the code for traversing a table.
by John B Oliver
This is an alternative for "Traverse a MSSQL table without using CURSOR"
by sukeshchand
Unexpected SQL Interview Questions
by salchichurria
Triki game created in SQL Server with triggers.
by Wendelius
TrimChar function which removes occurences of the desired character from both ends of a string.
by Smitten Ediot
Reporting stored procedure error in email and also log the error in a table.
by Paul M Simpson
Expanding a string by inserting alternating single spaces between characters
by pankajupadhyay29
A nice way to get aggregated value without group by
by Mycroft Holmes
Reparenting a Tree branch is a PITA using the HierarchyID functions. This reparents a branch by reformating the string representation of the HierarchyID. Supports moving the branch to the root node. I use an ID as the primary key so the proc expects the ID's of the node recordsDECLARE @NodeID INT
by Member 12574862
A new approach of calculating next N business days's date, provided we know the start date and the N number
by Brad Joss
A SQL String Split function for the real world
by Brad Joss
Search your SQL code with simple T-SQL statements.
by Amey A khedekar
A scenario with data type of the resultant select columns with UNION.
by Wendelius
How to overcome the error message "Types don't match between the anchor and the recursive part in column..." for varchar columns in a recursive CTE query
by Thiago Gaidzinski
UniDAC allows you to connect your cross-platform application directly with many database's types.
by Naresh Patidar
Insert, update and delete operations using stored procedure and DataAdapter in C#
by Mel Padden
How to update the schema of a temp table in a Stored Procedure in SQL Server
by Jeff Balcerzak
You might also want to try using a table variable - like this:DECLARE @tableName TABLE ( Key1 INT, Key2 INT, Description NVARCHAR(255), AggAmount FLOAT,)Then you can refer to your table by @tableName. Granted this is SQL Server 2005 and above, but then...
by Mannava Siva Aditya
Uploading an image and displaying it on the UI page
by chetan virkar
Uploading Zip File in ASP.NET
by #realJSOP
A scalar function to determine if a given DateTime is one of the ten US federal holidays, using SQL Server.
by John Gathogo
Catastrophic results associated with unqualified use of columns belonging to tables referenced on main query in a subquery
by Joe Leibowitz
Build a simple GUI in PowerShell that will display data queried from a SQL Server table.
by Tecfield
Beware of What We Ask Them to Do
by DrABELL
Generate large data series by using Cartesian Product and small data table
by rajeshitpro
Union All,Select
by db_developer
Reminder.Sou...
by db_developer
IF OBJECT_ID (N'dbo.GetIntervalStartDate', N'FN') IS NOT NULL DROP FUNCTION dbo.GetIntervalStartDate;GO--gets first day of interval date belongs toCREATE FUNCTION dbo.GetIntervalStartDate (@Date datetime,@IntervalType int = 0--0 - DAY, 1 - WEEK (Mon to Sun), 2 - MONTH, 3 -...
by IAndreev93
Standard functions usage, and my own functions... Allowing you simpler process tables... Date and time... Strings...
by Reeshabh Choudhary
Web platform based query builder to play with your database :)
by blnreddy
SQL Server built-in functions Coalesce()
by Gordon Kushner
By using recursion (and CROSS JOINS), you can generate data without looping or hard-coding INSERT statements into a temporary table.In the example below, you can use recursion to generate a week of scheduling data for three employees. -- Count variable, set to 7 for a week's worth of...
by Roger C Moore
This tip is a guide for using the Codeplex project Effort for testing Entity Framework applications without requiring the unit tests to actually hit the SQL Server database.
by KapilDevTripathi
Write a sql query in which we use only one IsNull() function and it will remove all Null values(if any) from entire result set(from all rows)
by Darek Danielewski
The combined use of Pipeline and NullObject patterns greatly simplifies data processing
by pankajupadhyay29
Nice and fast way for reporting
by Feleke Feyissa
select * from(SELECT l.Prepared_Date as Prepared_Date , m.Material_Code as Material_Code ,n.Name as Name,n.Description as Description , m.Quantity as Quantity,n.Unit_Of_Measure as Unit_Of_Measure , m.Status as Status...
by Kannan K R
select ExDate, SUM(case when Dept='A' then expense else 0 end)[Store A Expense],SUM(case when Dept='B' then expense else 0 end)[Store B Expense],SUM(case when Dept='C' then expense else 0 end)[Store C Expense]from expenseTable where Dept in ('A','B','C') group by ExDate
by mravikiran
Using ROWGUIDCOL in SQL Server
by Måns Tånneryd
This tip shows how to significantly speed up inserts of large amounts of data using the entity framework.
by Måns Tånneryd
This tip shows how to speed up inserts using POCO objects and the entity framework version 5.
by Måns Tånneryd
How to use bulk insert with your LINQ-to-SQL datacontext
by RupertC
If the order of your columns is different in the LINQ to SQL class from that in the database, then you also need to add a column mapping to the bulk copier. Otherwise you get mysterious errors in some of the loaded columns!In my simple fix, I assume that the names match even if the order may...
by S.Kaur
This will help you generate columns dynamically in SSRS reports using Matrix control.
by S. M. Ahasan Habib
I will explain here how to use table variable and over come cursor limitation
by Brad Joss
Views to make analyzing SQL Agent Job statistics easier
by Indrajeet Sutar
While using stored procedures, we need to pass SQL parameteres to those stored procedures. When there are large numbers of parameters then it is become boring task or tedious job to debug and check what values passed with. Here I have created a function that will check the values passed to...
by Michael Ecklin
Sometimes, we need to compare 2 tables to see what was changed. This tip shows you 2 different ways to compare data.
by Deepak A S
An ALL SERVER trigger to know who it is!
by OriginalGriff
Why? Normally, it's because you stored it wrong...
by Afzaal Ahmad Zeeshan
A slight comparison of ASP.NET upon other (web) programming languages in the market and a discussion of me and some other (web) programming language developers.
by Ilka Guigova
In dealing with durations in MSSQL server, I have found the following three resources helpful: :thumbsup: If you need to report a duration in a certain granularity such as "Task runs for ## minutes ## seconds", then refer to this[^] post:/*CREATE TABLE Tasks( ID INT IDENTITY PRIMARY...
by Oussama_Kahoul
Introduction to WPF technology and the MVVM design pattern
by alifaraze
writing error in a text file is very easy but writing error from a custom assembly in reporting services requires permissions
by rakesh1503
Writeback and writethrough using C# with SQL Server 2008 SSAS.
by Altaf Ansari
Dynamic creation of an SQL table by using an XML file, and importing data from an XML file to an SQL table.
by bbsimonbb
World first implementation of the Dominic Strauss Kahn data access method!