Click here to Skip to main content
15,886,664 members
Everything / Database Development / SQL Server / SQL Server 2012

SQL Server 2012

SQL-Server-2012

Great Reads

by AshishShukla6
This tip describes step by step implementation of executing stored procedure having user-defined table type as a parameter in entity framework using EntityFrameworkExtras package.
by Sarathi Balakrishnan
Reset SQL server SA (System Admin) Password when you have lost all possible ways to connect to SQL server and your server has only Windows authentication disabled. You should have Windows administrator permission to do this.
by AhsanAhmed
A brief introduction on how to use FOR XML clause in AUTO mode in Microsoft SQL Server to return data in XML format
by DiponRoy
How to do string split and join in SQL Server

Latest Articles

by DiponRoy
A utility query to find table generations in SQL Server relational database
by DiponRoy
How to do string split and join in SQL Server
by Micah Nikkel
SQL script that dynamically generates the DR scripts for failing over/back all Log Shipped databases. While it makes even a single database failover/failback a more streamlined process, it's most helpful for servers with multiple databases, such as SharePoint, consolidated SQL Servers, etc.
by Luca Astolfi
User defined procedure for make an HTML table from T-SQL Select statment

All Articles

Sort by Score

SQL Server 2012 

26 Sep 2015 by AshishShukla6
This tip describes step by step implementation of executing stored procedure having user-defined table type as a parameter in entity framework using EntityFrameworkExtras package.
21 Sep 2015 by Sarathi Balakrishnan
Reset SQL server SA (System Admin) Password when you have lost all possible ways to connect to SQL server and your server has only Windows authentication disabled. You should have Windows administrator permission to do this.
2 Jun 2017 by AhsanAhmed
A brief introduction on how to use FOR XML clause in AUTO mode in Microsoft SQL Server to return data in XML format
19 Feb 2019 by DiponRoy
How to do string split and join in SQL Server
29 Aug 2018 by Micah Nikkel
SQL script that dynamically generates the DR scripts for failing over/back all Log Shipped databases. While it makes even a single database failover/failback a more streamlined process, it's most helpful for servers with multiple databases, such as SharePoint, consolidated SQL Servers, etc.
7 Feb 2015 by Gaurav_Chaudhary
This tip is a brief introduction to Pivot operator in SQL Server
15 Feb 2015 by Bohdan Stupak
This tip shows some primary issue which puts a serious limitation on SQL Server MONEY data type.
21 Jun 2015 by Kornfeld Eliyahu Peter
Say it aloud for yourself in English...'Please select me the date from the table BreakFast where EPF_Number'...Where EPF_Number, what?Where clause is incomplete as there is no actual condition in it...In any other aspect too you query is wrong - check CONVERT function[^] of SQL to see...
6 Sep 2015 by Math08avan
Import text file data to SQL database using foreign key relation and validation.
18 Dec 2015 by Md. Marufuzzaman
This tip shows you an easy way to split Microsoft SQL Server table row data.
27 May 2013 by Tharaka MTR
Generate insert statements from a specific table data using SQL Server
10 Jun 2014 by Peter Leow
Refer: Sort AlphaNumeric Data in Sql[^]
19 Jul 2014 by Tim Golisch
The Master database often seems to be the "Lost & Found" bin of the SQL Server world. There are two popular ways for preventing this kind of problem. Read on...
20 Jul 2015 by F-ES Sitecore
If the user spends 2 seconds per row it would take them 27 hours to look at your gridview. Returning that amount of data is a very bad idea for many, many reasons, some of which you are finding out now. Use paging or implement some sort of filtering\search. Why present data that is useless?
23 Jul 2015 by Wendelius
Datetime2 is more accurate than datetime which has only accuracy for milliseconds.From datetime2 (Transact-SQL)[^]: When the fractional precision of the datetime2(n) value is greater than three digits, the value will be truncated.The following example shows the results of converting a...
24 Aug 2015 by Wendelius
I would say that the statement causes an error since you're missing an ending parenthesis for the values.Try usingSqlCommand cmd = new SqlCommand("Insert into...
7 Sep 2015 by Sergey Alexandrovich Kryukov
Strictly speaking, the choice of the database engine has nothing to do with MVC or any other framework on top of ASP.NET. It's enough that it worked well with ADO.NET. This choice should take into account the requirements of your application, which you did not share with us. But please don't do...
6 Oct 2015 by CPallini
Try this:using System;public class Program{ static void by_value(int x) { x = 42; } static void by_reference(ref int x) { x = 42; } public static void Main() { int i = 0; by_value(i); Console.WriteLine("after by_value, i = {0}", i); ...
25 Apr 2016 by Suvendu Shekhar Giri
You can use UPDATE with JOIN to do this.Check something like following-UPDATE S SET S.salary=S.salary+(S.salary*(CASE WHEN R.[role]='a' THEN 0.2 WHEN R.[role]='c' THEN 0.3 ELSE 0 END))FROM sal SINNER JOIN map M ON S.empid=M.empidINNER JOIN rolemaster R ON R.roleid=M.roleidI...
27 Jun 2016 by Maciej Los
In addition to solution1 by OriginalGriff[^], i'd strongly recommend to read this article: Visual Representation of SQL Joins[^]
1 Jun 2017 by AhsanAhmed
A brief introduction on how to use FOR XML clause in EXPLICIT mode in Microsoft SQL Server to return data in XML format
21 Aug 2019 by Maciej Los
Initial note: i think the answer to your question is opinion and experience based only. Quote: - What is the preferred way of handling this kind of situation? Well, there are possible two ways to store dates in a database: 1) UTC time or 2) DateTime + Offset The second method is recommended...
8 Jan 2020 by Wendelius
Since you're using an aggregate you need to give an alias to the column if you want to reference it by name. For example Statement s = con.createStatement(); ResultSet rs = s.executeQuery("select Max(CarNumber) AS MaxCarNo from CarRegistration"); rs.next(); rs.getString("MaxCarNo"); if...
23 Oct 2012 by aasim abdullah
How to use DELETED and INSERTED virtual tables to capture data change in result of any INSERT, UPDATE or DELETE statement.
24 Oct 2012 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.
17 Feb 2013 by Tharaka MTR
How to count consecutive dates using SQL
22 Oct 2013 by Mike Meinz
I tested both queries in SQL Server Management Studio. I turned on "Include Actual Execution Plan".The first query required one join and two index seeks/scans.The second query required three joins and four index seeks/scans.
4 Apr 2014 by Schatak
Try this:UPDATE YourtableSET datetimecol = DATEADD(day, DATEDIFF(day, datetimecol, getdate()), datetimecol)
21 Apr 2014 by Zoltán Zörgő
"Forgor password" functionality does not mean sending old plain text password to the user. Not at all. Actually this is the most vulnerable point in an application, since you have no control over what's happening. Generating one-time-password and sending that one to the user and forcing the user...
4 May 2014 by Maciej Los
Notes provided by Sander Rossel are very useful. It could be shortly described: start with basics!WOW, 11 tables!Another note is: I'd suggest to decrease the number of tables at least to 3 :)RegistrationItemTypeItemsCollectionRegistrationCreate Table...
10 May 2014 by sankarsan parida
You can do it in your storeprocedurechange on this lineSet @SubscripID = (Select TOP 1 SubscriptionId from TblSubscription where UserId = @Userid and IsActive = 1)Use more conditions in where clause to return single and right value in a subquery.
9 Jul 2014 by Jason Parms
Lightweight Directory Access Protocol (LDAP) Injection
13 Aug 2014 by Amol_B
Hello ,I am facing a weird issue with tables in my database.Tables in my application are created with a primary key defined (with Clustered index).Identity seed is a one for all tables in my database (IDENTITY(1,1)).CRUD operations are done on these databases using stored procedure...
13 Aug 2014 by Gupta Poonam
You might find your answer here..[^]
14 Sep 2014 by George Jonsson
As you don't specify any columns only a generic SELECT statement can be given for the value caseSELECT specific_column_nameFROM table_nameWHERE another_column_name operator value;For this to work, the values in the another_column_name must be unique.Another option is to use a...
1 Dec 2014 by Maciej Los
There is a bit difference between char and varchar[^] data types:char [ ( n ) ] Fixed-length, non-Unicode character data with a length of n bytes. n must be a value from 1 through 8,000. The storage size is n bytes. The SQL-2003 synonym for char is character.varchar [ ( n | max ) ] ...
17 Mar 2015 by Sergey Kizyan
This article explains how to merge your local SQL DB content to Azure DB from scratch
10 Apr 2015 by Rajeesh Madambat
Refer and write your own business logic in C# and add it to SSIS script task.
2 Jul 2015 by John C Rayan
Your result works as expected. 03/2010/15 is in MYD format so it returns 1. If you set to DMY format you might return 0.Check the documentation here https://msdn.microsoft.com/en-us/library/ms187347.aspx
20 Jul 2015 by Afzaal Ahmad Zeeshan
You are mixing a combination of Bad UX and Bad UI in your web application. First of all, you are well aware that web applications need network traffic so sending this much huge data (even if this takes 5 MB of network size) would never be a good idea. Pagination is used to minimize the network...
28 Jul 2015 by Suvendu Shekhar Giri
I don't see any problem doing that.Something like following should work.Your first viewCREATE VIEW [TestView1]ASSELECT 1 AS Id, 'Test 1' AS ValueUNIONSELECT 2,'Test 2'GOOUTPUT 1Id Value______________1 Test 12 Test 2Your second viewCREATE VIEW...
29 Jul 2015 by Kornfeld Eliyahu Peter
To open up you WHERE clause...STATION_ID = 'AIN SEBOU' AND SENSORNAME = 'NIVEAU')OR(STATION_ID = 'AIN SEBOU' AND SENSORNAME = 'PLUIE1HR')OR(STATION_ID = 'AZZABA' AND SENSORNAME = 'NIVEAU')OR(STATION_ID = 'AZZABA' AND SENSORNAME = 'PLUIE1HR')Where the last line actually not as you...
13 Sep 2015 by OriginalGriff
Um...UPDATE MyTable SET [No] = [No] + 9
28 Oct 2015 by Zoltán Zörgő
Wait a second.1) IIS does not connect to any RDBMS, except for storing session state - it is only a setting you can use in your application2) SQL Express does not enable TCP/IP connector by default, you need to enable it[^].3) For this to work, you need to have specific port level...
16 Mar 2016 by OriginalGriff
Assuming you have the dates in VB, they should be in DateTime values.So...Dim diff As Timespan = realDeliveryDate - confirmedDeliveryDateIf you don;t have them as DateTime values, then convert them to DateTime using DateTime.TryParseIf they are in SQL, then again, they should be DATE or...
21 Aug 2016 by OriginalGriff
Try:SELECT * FROM MYTable aJOIN (SELECT CustName FROM MYTable GROUP BY CUSTName, DATEPART(ISO_WEEK,PurchaseDate) HAVING COUNT(PurchaseDate) >= 5) bON a.CustName = b.CustName
21 May 2019 by phil.o
Connect to SQL Server When System Administrators Are Locked Out[^] may help.
17 Sep 2012 by Stephen Hewison
There was something wrong with the report definition. It wasn't updating the parameter definitions to use the default values.After deleting the report from the server and republishing it, the default values were applied.
5 Nov 2012 by fjdiewornncalwe
www.connectionstrings.com[^] is a great site that can help you build your connection strings. Just go there and navigate to the MySQL page and pick the type of connection string you need from there.Cheers.
9 Jan 2013 by aasim abdullah
SQL Server: A Query Slow in SSMS, Fast in Application, WHY?
3 Feb 2013 by skydger
Try to use SqlDateTime type. System.Data.SqlTypes.SqlDateTime m_dtm = System.Data.SqlTypes.SqlDateTime.Parse(txtMelliCodeReport.Text); adp.SelectCommand.Parameters.AddWithValue("@clrk_MelliCode", m_dtm); System.Data.SqlTypes.SqlDateTime az_dtm =...
4 Apr 2014 by Peter Leow
Refer: sql_insert_into_select[^]
4 Apr 2014 by Schatak
Are you storing images in database or just paths to images?First , you need to take care few things if you are fetching your images from database then you need to set image source property to "Database" but if image is not saved in the database, but only the path to it then changed it to...
4 Apr 2014 by Schatak
create table employee( employeeId int not null, employeeUsername varchar(50) not null, employeePassword varchar(50) not null, employeeName varchar(50) not null, employeeContact int not null, employeeEmail varchar(30) not null, Constraint PK_Employee PRIMARY...
4 Apr 2014 by Guruprasad.K.Basavaraju
create table employee( employeeId int not null, employeeUsername varchar(50) not null, employeePassword varchar(50) not null, employeeName varchar(50) not null, employeeContact int not null, employeeEmail varchar(30) not null, primary key(employeeId));...
8 Apr 2014 by Schatak
You are making mistake.correct itSELECT @COUNT=COUNT(*) FROM emp_table
8 Apr 2014 by ArunRajendra
Try this method.select convert(varchar(100),GETDATE(),108)
8 Apr 2014 by Schatak
SELECT distinct Profile,stuff((select distinct ', ' + Specialization FROM TM_Specialization tms INNER JOIN TM_Profile tmpON tms.ProfileID=tmp.ProfileID where tms.ProfileID =tm_p.ProfileIDFOR XML PATH('')) ,1,1,'') as SpecializationFROM TM_Profile TM_P INNER JOIN TM_Specialization...
15 Apr 2014 by CHill60
sanket saxena is correct.Specifically look at these linesdeclare short cursor for select Message,Mobileno,MSgdelivered,Replymsg from Shortcode_Course_SMS where Msgdelivered > @Fromdate and Msgdelivered
23 Apr 2014 by OriginalGriff
Um...You declare four parameters, but you only provide three in your call - and in the SP you try to declare a variable with the same name as one of the parameters: @artistIdI suspect that you didn't mean to include @artistId in the parameters list.
24 Apr 2014 by thatraja
Check theseBeginners guide to a secure way of storing passwords[^]&Password Security[^]The Art & Science of Storing Passwords[^]
30 Apr 2014 by CHill60
The following will answer your question as you have asked it...Declare @LatePayCharge intset @LatePayCharge= 60insert into tblbill (SocietyID,MemberID,BillDate,AmountRemaining,LatePayPenalty) select I.SocietyID,I.MemberID,CAST(GETDATE() AS DATE),I.TotalCharges,@LatePayCharge from...
6 May 2014 by thatraja
Check this article6 ways of doing locking in .NET (Pessimistic and optimistic)[^]
10 May 2014 by Manas Bhardwaj
You could start something like this:Btw, the core of writing a program is logical structure than the actual syntax.CREATE PROC uspSetSubscriptionPayment @PayMethod varchar(50), @PackageType varchar(25), @Userid int, @ConstID int, @SubscriptionIdentity int...
11 May 2014 by DamithSL
you need to use cast as below (@StreetNo IS NULL OR @StreetNo = 0 OR StreetNo LIKE cast(@StreetNo as varchar(10)) + '%')check this SQL Fiddle[^]
20 May 2014 by Aaron Hartley
I have a C# windows application written in VS 2010 that uses SQL Server Express database as the back-end. I'm finding that I have a need for having different users with different rights, to limit how much damage can be done by careless users. For example, one highly trusted user can mass delete...
21 May 2014 by nilschaudhari
Hello,Create Stored Procedure for the same. Use the If Condition in the procedure as followsCreate procedure procedurename(parameters)DECLARE @mode INT;SET @mode = 0;IF @mode = 0 then SELECT t.Column1,Count(t.Column2) as Column2FROM Table1 t--Where some list of...
22 May 2014 by Arjun Holla
http://www.bimonkey.com/about-the-bi-monkey/support/ssis-component-samples-list/[^]
21 Jun 2014 by george bolovan
Read data from the next row
13 Aug 2014 by OriginalGriff
Never seen or heard of that as a problem: and SQL Identity fields are used so often I'm pretty sure it would show up.Are you sure that is exactly what is happening? It would be easy to see that kind of change if rows are deleted for example, since the identity values will not be...
16 Aug 2014 by Homero Rivera
FYI - Your tables are not following some basic standards, such as using the same column name for things that are meant to be the same (e.g. RegisteredProducts.PackageType and Packages.PackageType).Be careful with that.also, the result set you want to see looks more like an Excel pivot to...
8 Sep 2014 by hypermellow
Have a look at MSSQL's procedure sp_executesql.sp_executesql allows you create a dynamic string containing the SQL statement to run, so you should be able to incorporate you dynamic table name into the SQL statement.Hope it helps.
8 Sep 2014 by Stephen Hewison
You need to use Dynamic SQLThere is an SQL command called sp_ExecuteSQLThis will allow you build a string such as this and execute it:DECLARE @MySQL VARCHAR(MAX)SET @MySQL = 'SELECT * FROM DestinationDatabase.dbo.' + @TableNameEXEC sp_ExecuteSQL @MySQLWARNING!!! WARNING!!!...
10 Sep 2014 by Gihan Liyanage
Copy Table Schema and Data From One Database to Another Database in SQL Server[^]
14 Sep 2014 by george4986
-----------sample table structureSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [dbo].[area]( [area_id] [bigint] NOT NULL, [area_code] [varchar](10) NULL, [area_name] [varchar](50) NOT NULL, [latitude] [float] NOT NULL, [longitude]...
26 Sep 2014 by Anil kumar Bhardwaj
Export all the primary, Unique, Foreign key and default constraints from existing database
4 Oct 2014 by Zoltán Zörgő
As I mentioned before, google is your friend. You can start here: http://www.serverintellect.com/support/sqlserver/database-backup-ssmse/[^]
23 Oct 2014 by essentialSQL
How to Group and Summarize your Results in SQL
23 Oct 2014 by essentialSQL
Query Results Using Pattern Matching in SQL
24 Oct 2014 by essentialSQL
How to sort your query results in SQL Server
21 Nov 2014 by /\jmot
Links..http://techbrij.com/html5-geo-location-sql-server-asp-net[^]http://msdn.microsoft.com/en-us/library/bb895266(v=sql.105).aspx[^]
10 May 2015 by Osama Abu Sitta
what is difference between ‘WITH NO CHECK’ and ‘NO CHECK’ in SQL Server ??
11 May 2015 by Member 11039257
Using WITH NO CHECK:We have a table with 100 records.1)Now we are creating a foreign Key Constraint by altering that tableALTER TABLE [Sales].[SalesOrderDetailTemp] WITH NOCHECK ADD CONSTRAINT [FK_SalesOrderDetailTemp_SalesOrderHeader_SalesOrderID] FOREIGN...
21 May 2015 by King Fisher
Hi,I doesn't matter how many tables we are going to join, the thing is you should clear in the concepts of join, if you are well clear then you can do whatever you want.here is the good article about joins,please read...
15 Jun 2015 by OriginalGriff
Remove the quotes:string query = "SELECT SUM (COUNT) FROM Count_EPF WHERE date = '@C' ";Becomes:string query = "SELECT SUM (COUNT) FROM Count_EPF WHERE date = @C ";Otherwise the parameter name is within an SQL string and is not treated as a parameter at all.[edit]Oh, and don't pass...
28 Jun 2015 by Suvendu Shekhar Giri
Try this-SELECT [Date],Price FROM Dataupload WHERE [Date] BETWEEN DATEADD(DAY,-8,GETDATE()) AND DATEADD(DAY,-1,GETDATE())Hope, it helps :)
1 Jul 2015 by Maciej Los
Have a look at sample:DECLARE @tmp TABLE(CustomerID INT, SequenceNo INT, Comments VARCHAR(MAX))INSERT INTO @tmp (CustomerID, SequenceNo, Comments)VALUES(1, 1, 'ABC D'),(1, 2, 'CDE'),(1, 3, 'ABC'),(1, 4, 'ABC D'),(1, 5, 'CDE'),(1, 6, 'abc'),(2, 7, 'ABC DEF'),(2, 8,...
13 Jul 2015 by OriginalGriff
Use NULLIF[^] - because NULL propagates in SQL, it will cause the whole calculation to return NULL instead of throwing an exception.ROUND(((OverListedPrice/NUFFIF(listedprice,0))-1)*100,3) as overlistedpercentageBecause division by zero is mathematically an error for all practical purposes,...
21 Jul 2015 by Suvendu Shekhar Giri
Although your question is not clear, the error in you query was unwanted "as Support" in between the case when statement.syntactically corrected query is-case when Business_Group like '%Back Office%' then bonus else bonus end as ALCBut this is something you never want as result, what I...
23 Jul 2015 by Suvendu Shekhar Giri
You can rewrite it using CASE WHEN as-SELECT @Principal= CASE WHEN optionfieldvalue='' THEN NULL ELSE CAST(optionfieldvalue as decimal(38,18)) END FROM @DATA WHERE TemplateFieldId = 47Hope, it helps :)
23 Jul 2015 by Suvendu Shekhar Giri
Here I got the solution. I have posted the same question in Stackoverflow[^]Quote:The reason is that in datetime type, you only have .000, .003 and .007 fraction of a second.Try this:select cast('2015-01-01 00:00:00.882' as datetime)select cast('2015-01-01 00:00:00.884' as...
24 Jul 2015 by barneyman
that's not really how SQL is designed, SQL will only lock the row/page when you start the update transaction - if you want to mark a row 'out of bounds' for editing, you'll have to implement your own lock mechanism ... perhaps a nullable datetime column on each row, which marks that row as being...
28 Jul 2015 by OriginalGriff
Name the views:SELECT a.Col1, b.Col1, a.Col2, b.Col2, a.Col3 FROM View1 aJOIN View2 bON a.Col1 = b.Col1
28 Jul 2015 by Wendelius
A simple way would by to use EXCEPT to remove existing values from all values. Consider the following exampleSELECT all_values.IdFROM (SELECT 1234 AS Id UNION ALL SELECT 9999 AS Id UNION ALL SELECT 8888 AS Id ) all_valuesEXCEPTSELECT IdFROM MyTableFor more...
6 Aug 2015 by Richard Deeming
As mentioned in the comments, a stored procedure would be a better approach. However, you can still do it with inline SQL:const string query = @"DECLARE @EmpID int;INSERT INTO EMP (empname, empdate) VALUES (@Name, @Date);SET @EmpID = Scope_Identity();INSERT INTO DEP (deptname,...
23 Aug 2015 by Duncan Edwards Jones
First creaste a generic "split"[^] function, like so:-CREATE FUNCTION dbo.fnSplit( @sInputList VARCHAR(8000) -- List of delimited items , @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items) RETURNS @List TABLE (item VARCHAR(8000))BEGINDECLARE @sItem...
23 Aug 2015 by Maciej Los
As to OP's comment:Member 11917248 wrote:IS IT NOT POSSIBLE TO SOLVE IN A SIMPLE WAY WITHOUT USING FUNCTIONYes, it is posible to get result using CTE: get 2nd and 3rd string by splitting a long string using T-Sql[^]
26 Aug 2015 by Afzaal Ahmad Zeeshan
That is exactly why Content management systems[^] were introduced. You can create a system for your applications so that your clients are provided with features, in a GUI mode. They don't even have to change anything, they can apply templates, change the content, update or even delete the...