Click here to Skip to main content
15,892,537 members
Everything / Programming Languages / T-SQL

T-SQL

T-SQL

Great Reads

by dale.newman
Google your SQL.
by honey the codewitch
Embed fast streaming C# code to match text based on inputted regular expressions
by DaveDavidson
In this article, I show LINQ to Entities syntax that will produce queries with CROSS APPLY and LEFT OUTER JOIN clauses.
by Ed Wiebe
Can't we obtain the benefit of using bitwise operators for SQL many-to-many relationships AND maintain referential integrity?

Latest Articles

by Federico Di Marco
spSearchTables: a helper T-SQL stored procedure for digging into (large) databases
by Dathuraj Pasarge
Extract SQL Server DB inventory\baseline using TSQL and PowerShell scripts
by Sergei Y.Kitáev
Introduction to statically parameterized SQL language
by honey the codewitch
Embed fast streaming C# code to match text based on inputted regular expressions

All Articles

Sort by Title

T-SQL 

29 Oct 2011 by ShacharK
I'm executing my procedures from my C# code, and for some reason I can't see their effects on the server's tables.Is there anything else I need to do except for executing them? What could be the cause for this annoying problem?EDIT:This is an example for a procedure:public void...
29 Oct 2011 by Mehdi Gholam
Run your program using the SQL tracer and see what parameters are being passed to your stored procedure and what is happening on the server.EDIT :Read this : How To: Use SQL Profiler[^]
30 Oct 2011 by ShacharK
I'm currently have this query:IF NOT EXISTS(SELECT * FROM Table1 WHERE Value = 1)BEGINDELETE FROM Table2 WHERE Value = 1ENDIs it possible to use INNER JOIN, to delete all the rows from Table2 if a value doesn't exist in any of the other table's rows. Because using this would...
30 Oct 2011 by Amir Mahfoozi
delete table2 where value not in (select value from table1)Hope it helps
30 Oct 2011 by Abhinav S
Try DELETE FROM table1WHERE NOT EXISTS ( select value from table2 where value = 1 )Warning: I have never run a similar query myself.
30 Oct 2011 by Sander Rossel
Yeah, you can simply delete rows from a table using an INNER JOIN.DELETE t2 FROM table2 AS t2INNER JOIN table1 ON table1.Value = t2.ValueWHERE table1.Value = 1MSDN mentions joins in delete statements: Delete Statement[^]Here is a full example: Delete with INNER JOIN[^]Hope that helps :)
28 Oct 2011 by ShacharK
What is the most efficient way to execute the following SQL "Pseudo-code" (within a STORED PROCEDURE):SELECT PKEY_ID_COLUMN FROM table1 -- SELECT all the ID values from table1... (lets say 1,2,3)-- Now, insert to another table the value 1 (for example...) along with each and every...
28 Oct 2011 by Mehdi Gholam
Use insert into ... selectinsert into table1 (id1, table1id) select id as [id1], column as [table1id] from table2
28 Oct 2011 by Corporal Agarn
If using T-SQL:INSERT INTO relational_table (ID1,table1ID)SELECT 1, PKEY_ID_COLUMN FROM table1
28 Oct 2011 by Arasu Rajendran
U can use cursor to do this...use following procedure,create proc addid_sp(@eid int)--table2 idasbegindeclare @uid int--table1 iddeclare curUid cursor for select * from tblIdopen curUidfetch next from curUid into @uidwhile @@FETCH_STATUS=0begininsert into tbleid...
29 Oct 2011 by ShacharK
I have this extremely simple procedure, and for some reason it works when I'm activating it using the Visual Studio's Database thingy, but fails when I'm using it from my code (the extracted value is 0 instead of 1 when there's such a user).CREATE PROCEDURE Client_Authenticate (@ID...
29 Oct 2011 by Not Active
Visual Studio Database thingy? I'm unfamiliar with that tool :)There would be no reason a stored proc would work in one environment and fail in another. Make sure you are connecting to the same database and you are handling any exceptions. You can also SQL Sever profile to monitor what is...
12 Jan 2011 by Member 1450550
Hi there,I have been racking my brains on this for a little while now. I am writing a category driven website for a friend and need a way to extract the number of levels the categories go down in a table.To explain, instead of sticking to maybe 3 levels:Main Category > Sub Category...
12 Jan 2011 by Steven J Jowett
Google for T-SQL Recursion[^]. You will find plenty of examples of what you are trying to do.
12 Jan 2011 by Estys
SQL is poor in hierachical data. This article may help : http://www.sqlteam.com/article/more-trees-hierarchies-in-sql[^]Also look into this : Building hierarchy using Recursive CTE[^]This will give you an insight in how your problem can be solved.Cheers
12 Jan 2011 by Espen Harlinn
Use Common Table Expressions:http://www.4guysfromrolla.com/webtech/071906-1.shtml[^]orBuilding hierarchy using Recursive CTE[^] by Hiren SolankiRegardsEspen Harlinn
12 Jan 2011 by Member 1450550
Thank you all for your help but after doing what Seven suggested and googling mysql recursion I found a different approach using nested categories at this link:http://dev.mysql.com/tech-resources/articles/hierarchical-data.html[^]This seems a much more fluid approach then to doing lots...
27 Mar 2012 by Marian Placko
This article shows a simple hack of a built-in MS SQL Server WITH ENCRYPTION mechanism
20 Sep 2017 by leocode7
Hello Everyone, Please Tell me if is possible to set the property ProfileInputXml of the Data Profile Task in SSIS with a variable, because i want to set the property dinamically with expression options, I Attached a image to show more better the problem. Bugs - Google Drive[^] If there is a...
1 Apr 2012 by Member 8642100
Hi there, I need a select statement group by, count, average and max. This is what i have so far but i still have error. Can anyone tell me where I went wrong?SELECT [Name], count (*) as cnt, MAX([Duration]) as maxDur, format AVG([Duration]) as avgDur FROM tbContractors groupby...
1 Apr 2012 by anshudutta
you are missing the Having cluase
1 Apr 2012 by Member 8642100
I've got it by using access query..SELECT tbContractors.Name, Avg(tbContractors.Duration) AS AvgOfDuration, Max(tbContractors.Duration) AS MaxOfDuration, Count(tbContractors.Duration) AS CountOfDuration FROM tbContractors GROUP BY tbContractors.NameThanks.
17 Sep 2016 by Snorri Kristjansson
A SQL server CLR Stored Procedure that can query the Active Directory directly in T-SQL code
16 Nov 2010 by mazhou
Ad-hoc pagination support with SQL Server codenamed “Denali”
13 Mar 2018 by David Cleeton
I have two repeaters one nested inside the other. The first repeater creates 12 rows, one for each month of the year. It works out the number of days for each month in turn and adds them to an array. The array is then used as the datasource for the second repeater. The second repeater checks...
15 Dec 2010 by hector [.j.] rivas
Helping the combo box autocomplete function with a frequency count.
2 Nov 2014 by shailesh_pujara
I am passing Persian text as value of sqlparameter to a parameterized query in asp.net/vb.netbut returns no row - the same query i run in ssms - gives result rows. Don't understand where is the mistake. Database already collated 'Persian_100_ci_ai.Vb.net: Dim cmd As New SqlCommand ...
3 Nov 2014 by Bernhard Hiller
What about the AddWithValue function? I.e.cmd.Parameters.AddWithValue("@UserName", "ادمین")
3 Nov 2014 by Maciej Los
As PIEBALDconsult had mentioned in this[^] answer, remove this line:dt = Nothingfrom Finally block.It destroys your table!Do not repost!
21 Nov 2014 by shailesh_pujara
Thanks all for your answers. I found where I was wrong. There were two databases - English and Persian. The connection class which I have created to connect to appropriate database has bug and sometime due to bug it was connecting to English database i/o Persian. Now I resolved the bug....
1 Dec 2021 by ahmed_sa
I work on SQL server 2014 after add two stuff statement to script below it become very slow before add two stuff statement it take 28 second for display 500 thousand now as below script and after add two statement stuff take 5 minutes so how...
1 Dec 2021 by CHill60
1. Watch out for all the spelling mistakes with your table core_datadefinition_Details or core_datadefinition_Detailes or core_data_definition_Details - many members would not bother persisting through that to get your code to work. 2. As I...
6 Dec 2011 by Rene Bustos
Hi Guys. i have a question.what happend if i try to ALTER a Store Procedure while this is Runningit is possible?thanks in advanceEDIT:Thanks guysI gave you 5Regards from Mexico
6 Dec 2011 by Wendelius
Well basically nothing until the procedure is not in use anymore. After that the ALTER command is actually carried out and the procedure is changed.Yes, you can issue the ALTER statement even if the procedure is in use at the moment.
6 Dec 2011 by Mehdi Gholam
Yes, new calls will go to the changed procedure and the current executing procedure will continue as the older version.
19 Oct 2016 by Manjuke Fernando
26 Sep 2012 by szataniel
hello,i have a problem in sql server 2005 with rounding functions. for example i have declared variable as decimal and set a value to it:DECLARE @v DECIMAL(8,3)SET @v = 4.843now i have to round this value up to value 4.85. is there any possibility to do that? standard rounding...
26 Sep 2012 by Maciej Los
Test it:DECLARE @v DECIMAL(8,3)DECLARE @x DECIMAL(8,3)SET @v = 4.839SET @x = 0.001CREATE TABLE #tt ([V] DECIMAL(8,3), [AkaModuloV] DECIMAL(8,3), [RoundedV] DECIMAL(8,3))WHILE (@v
26 Sep 2012 by Aarti Meswania
see below exampleselect convert(numeric(18,2),2.237)you can use function convertconvert(numeric(18,2),Input value)orconvert(Decimal(18,2),Input value)Happy Coding!:)
26 Sep 2012 by Santhosh Kumar Jayaraman
try thisDECLARE @v DECIMAL(8,3)SET @v = 4.846SELECT Cast(ROUND(@v, 2) as decimal(8,2))this will give me 4.85DECLARE @v DECIMAL(8,3)SET @v = 4.843SELECT Cast(ROUND(@v, 2) as decimal(8,2))this will give me 4.84
11 Oct 2012 by szataniel
i have created a function with code:GOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOcreate FUNCTION [dbo].[VAT_Rounding](@brutto DECIMAL(16,3))RETURNS DECIMAL(15,2)ASBEGINDECLARE @vat DECIMAL(16, 3)DECLARE @b DECIMAL(16, 3)DECLARE @r DECIMAL(16, 3)DECLARE @c...
18 Dec 2016 by NightWizzard
Convert amounts to their spoken equivalents
15 Aug 2021 by Vijaya Simha 2021
I got this error when i ran the query. An expression of non-boolean type specified in a context where a condition is expected, near 'BEGIN'. If (select DATEDIFF(MINUTE,LastUpdatedDateTime ,getdate()) AS Diffinminutes FROM...
15 Aug 2021 by OriginalGriff
This isn't a boolean expression: If (select DATEDIFF(MINUTE,LastUpdatedDateTime ,getdate()) AS Diffinminutes FROM [sports_UAT].[dbo].[DB_Spots_UAT] where (DATEDIFF (MINUTE,LastUpdatedDateTime,getdate()) >10)) Let me simplify it for you so...
25 Nov 2015 by Manjuke Fernando
Analyzing SQL Server Error Logs / Agent Logs using T-SQL
29 May 2017 by tranthanhtu.vn
In this article, We will learn why do we need to manage the stages of our application.
29 May 2017 by tranthanhtu.vn
In this article, we will learn how to build and deploy the code
11 May 2015 by MedZi2010
Create a basic SSIS Package to enter the files provided in “ETL_Diagram Section Files” to anew Database called Curriculum. The SQL Script will be executed within SSIS in a SQL Task (The script may be too big to use in a SQL Task. In that case, find another alternative such as putting...
13 Aug 2014 by Liju Sankar
Hi,In the following query, Table 1 is used many times in order to get accurate Summary data. However when the total records in Table 1 increased to 400K, the query is taking more than 15 seconds to execute.Inviting your suggestion / view points to improve performance of this...
13 Aug 2014 by OriginalGriff
Never easy: it's going to take some work.This: http://www.anchor.com.au/hosting/dedicated/SQL_Query_Optimisation[^] provides good background, but it's not MsSql related (it's MySql/PostgreSQL) - the methods to do the analysis are different but the techniques are the same.Google will also...
14 Aug 2014 by Mangesh4
HiIf you are using same table then why should you used "from" clause every group.Use from clause only at once and apply multiple group function in single query.ThanksMangesh
14 Aug 2014 by Jörgen Andersson
The obvious solution would normally be the use of analytical functions to limit the number of table reads to just one.But SQLServer does not support Count(Distinct foo) over (Partition By Bar Order by Foobar)Luckily there's a workaround:SELECT DENSE_RANK() over (order by...
16 Nov 2015 by sandeepmittal11
Apply Operator in SQL Server
10 Sep 2018 by Manjuke Fernando
How to give db_datareader access to a specific user across all the databases on a particular SQL Server
19 Nov 2021 by CHill60
This question has been answered on the repost at How to use group by instead of distinct when make stuff feature name and feature value ?[^]
25 Nov 2021 by ahmed_sa
I work on sql server 2014 I need to get partc as expected result Actualy i need partc from table #partsc that have Verification Hash on table #VervicationCode are there are any way to get part c without join with Verification Hash expected...
25 Nov 2021 by OriginalGriff
That is what JOIN is for: SQL is very efficient at doing joins because they and Foreign Keys are the "glue" that binds tables together in a relational database. Use a JOIN: it's the "right way" to do it.
26 Jul 2017 by Ed Wiebe
Can't we obtain the benefit of using bitwise operators for SQL many-to-many relationships AND maintain referential integrity?
22 May 2022 by ahmed_sa
i work on sql server 2017 i need to use check sum for hashing but im afraid if i got stuck or issue when compare my data all will be numbers only or numbers with stick example of my data 121 121|145 155|233|2231| so are check sum hashing with...
29 Nov 2012 by RovenetBill
ASP.NET c# component for editing SQL tables with plug-in column format adapter architecture.
9 May 2013 by Chiranthaka Sampath
I have created the following Stored Procedure in an SQL Server Express Instance. I am using Visual Studio 2010 Professional and SQl Server 2008 Express edition.USE [LeaveMgt]GO/****** Object: StoredProcedure [dbo].[LeaveApply] Script Date: 05/10/2013 02:06:31 ******/SET...
9 May 2013 by Richard C Bishop
Try adding parameters like this: SqlParameter dataParameter = new SqlParameter(); dataParameter.Value = txtEmpNo.Text.Trim(); dataParameter.ParameterName = "@EmpNo"; SqlParameter dataParameter2 = new SqlParameter(); ...
9 Aug 2012 by Kailash_Singh
I have following querry:DECLARE @A intDeclare @R intEXEC SP_EXECUTESQL N'select new from tblMRM where [year]=year(getdate()) and [month]=CONVERT(CHAR(4), getdate(), 100)', N'@A VARCHAR(10) OUTPUT', @A OUTPUTselect @Ait has following output:new0(No column name)NULLWhen I...
9 Aug 2012 by ssd_coolguy
try below query:-DECLARE @A intDeclare @R intEXEC SP_EXECUTESQL N'select @A=new from tblMRM where [year]=year(getdate()) and [month]=CONVERT(CHAR(4), getdate(), 100)', N'@A VARCHAR(10) OUTPUT', @A OUTPUTselect @Ayour @a is output parameter and you must use it in sql query..
25 Apr 2022 by Lotus90
Hi I have database table where the id should increment automatically.I set the "identity specification to yes and increment it by 1 "also I put the "SET IDENTITY_INSERT MyTable ON " but I still have the error."Incorrect syntax near the word [table name]"How I Can insert to the...
27 Oct 2012 by Zoltán Zörgő
SET IDENTITY_INSERT ON(http://msdn.microsoft.com/en-us/library/aa259221(v=sql.80).aspx[^]) allows explicit values to be inserted into the identity column of a table.If it is OFF, you can not issue INSERT statements, that affect an identity filed.If you want an identity filed to work on...
27 Oct 2012 by Shambhoo kumar
Quote:CREATE TABLE Persons(P_Id int PRIMARY KEY IDENTITY,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))
30 Dec 2019 by Dathuraj Pasarge
Database mirroring setup without any DBA effort - on every new database creation
6 Jul 2014 by Prathap Gangireddy
Hi,Need advice with the below stored procedure to avoid concurrency problems..Create PROCEDURE [SD_SaveUpdate_DepartmentDetails] @DeptID int,@DepartmentName varchar(100),@DepartmentID int out AS BEGINBegin Try...
5 Jul 2014 by Prathap Gangireddy
Thank you all for the time.Without using the Locking concept(SET TRANSACTION ISOLATION LEVEL) or any UPDLOCK, i tried the below SPCreate PROCEDURE [SD_SaveUpdate_DepartmentDetails] @DeptID int,@DepartmentName varchar(100),@DepartmentID int out AS ...
9 May 2013 by PRANAV SINGH
Backing up all databases using T-SQL
24 May 2017 by GTR0123
Hello i have trouble in counting balance soo i am doing like this i am trying to select recoreds and then count balance. Table1 ID Name Value(money) Type(in, Out) Table2 ID StartBalance(this is constant and it's value 100) soo when i am selecting table i need to make temporary column where ...
24 Dec 2018 by Harpreet_125
below query is giving me customer id's. what i want is: i want to count total number of customers who have paid the installments from these id's. there is another table named as installments, there is a status column with values like 'paid' and 'not paid'. we have to count from installments...
24 Dec 2018 by Wendelius
It would help if you've posted some sample data. But let's try a few variations. If only a single payment can exist per customer then to list customers with payment, perhaps something like SELECT c.Cust_Id FROM user_detail c INNER JOIN installments i ON i.Cust_Id = c.Cust_Id WHERE c.Status =...
24 Nov 2013 by BrianHamilton
Hi,I'm messing around with databases to learn them and I have the following basic SQL which works fine:SELECT Name AS ProductName, StandardCost AS Cost, ListPrice AS PriceFROM SalesLT.ProductWHEREListPrice / 2
24 Nov 2013 by OriginalGriff
Without your actual data, it's pretty difficult to be precise, but...The operator precedence looks right - divide is done before
7 Feb 2014 by Vishal D Kolekar
When we have some calculated column in database for reports, which is best way to calculated it's value in case of SSRS report developement.1. Calculate it in SSRS tablix2. Calculate it from database and return as datasetIf I am duplicating this question then sorry for that, but I didn't...
19 May 2014 by aravinth04
We can do it in both the ways. I'm usually doing calculation in the backend itself. If you use aggregate controls like Total or something else, you should use expressions.
23 May 2014 by Member 7874525
I would prefer that if you simply want to apply aggregation like sum or average then you should do it at Report level but if you want to do calculations based on other columns values then it is better if you do at query level and then pass data set to the report.Consider cases,1. If you...
27 Mar 2014 by vicvis
Hi,I wish to send a mail to group of user once data is entered in a particular table.I am not sure which way to use,should I go for .Net program or should I use db_mail functioanlity of Sql Server.I was thinking of writing a trigger to send a mail once data is entered in table.Can you...
27 Mar 2014 by Mehdi Gholam
Triggers are a bad idea, since there is the potential to block the database, and in any case emails require retries etc. and are bound to the network latency.You are better off creating a service for this with retry and notification.
11 May 2018 by RedDk
I haven't asked a question for a long time but these two are so prescient that I'd be very surprised if the matter hadn't come up at some time in the experiences of many if not most CPians here at some point in their experiences using Visual Studio. First, has anyone ever BROWSED (not made an...
11 May 2018 by Dave Kreskowiak
You cannot use assemblies in your app that target a Framework version higher than the one your app is targeting. While you may find cases were this will work, there are plenty of cases where it won't, and it seems you just found one. This is specially so if your app is targeting .NET 2.0, 3.0,...
23 Nov 2012 by Rob Branaghan
Just a function to make populating a datetime variable easier!
26 Nov 2012 by André Kraak
This is an alternative for "Build a Date Function"
3 Nov 2014 by shailesh_pujara
I am passing sqlparameter in localize language (Persian) from c# but no rows retrieves. Database already collate for persioan_100_ci_ai and tables are collate database_defaultSqlCommand cmd = new SqlCommand();DataTable dt = new DataTable();SqlDataReader dr =...
3 Nov 2014 by Manas Bhardwaj
The code you have provided works for me. However, the first example wont even compile unless you change to this.fromcmd.commandtext = qry;tocmd.CommandText = qry;
3 Nov 2014 by Maciej Los
Instead of such of query:string qry = "Select * from users WHERE [Name]='" + pLoginName + "' AND [Pwd]='" + pPassword + "'";use stored procedure[^].For further information, please see:How to: Execute a Stored Procedure that Returns Rows[^]Walkthrough: Displaying Data Using a Stored...
3 Nov 2014 by PIEBALDconsult
I'm thinking it's this:} finally { dt = null;(Experimentation has ruled that out.)Let's try to simplify your code then -- and use using statements as well.DataTable dt = null ;using ( SqlCommand cmd = conn.CreateCommand() ){ cmd.commandtext = "Select * from...
21 Nov 2014 by shailesh_pujara
Thanks all for your answers.I found where I was wrong. There were two databases - English and Persian. The connection class which I have created to connect to appropriate database has bug and sometime due to bug it was connecting to English database i/o Persian.Now I resolved the bug....
25 Nov 2012 by giorgi111-111
Hello I'm developing project that will use online hosted database .in my windows forms app , I have some kind of schedule maker which makes notes and schedules based on user . I want to provide login form in this application which will be passed by registered ones and then edit their own notes...
24 Nov 2012 by DaveAuld
I would suggest entity framework.However, why use winforms? you could just as easily exapand the range and accessibility of the application, but simple using an MVC web app, coupled with Entity framework.You could knock up something like this relatively easily using those...
25 Nov 2012 by AlokZanwar1985
Hi as you are using windows application and you want to access DB which is hosted on Servermeans if your want to Login then they should have internet connection which can access this account simply in app.config file you need to add DB connection with user name and Password credentials which...
31 Aug 2013 by AjmLikeIt
How i can convert t-sql datetime to c# datetime?I always got InvalidCastException.code Employee:public Employee(string fName, string lName, int age, int earnings, DateTime dateOfRegistration) { this.First_Name = fName; this.Last_Name = lName; this.Age =...
31 Aug 2013 by OriginalGriff
Assuming that the data in your DB is stored as a DateTime column, then it should just be a case of casting it:emps.Add(new Employee((string)dr["First_Name"], (string)dr["Last_Name"], (int)dr["Age"], (int)dr["Earnings"],(DateTime)dr["Date_of_registration"]));If it isn't then you need to look at...
17 Mar 2017 by Andy Lanng
Hey,I am trying to restore a db with Microsoft.SqlServer.Management.Smo but I keep getting access denied.I have set up the service user for the instance (MSSQL$LOCAL2016) with full access rights to the folder The folder is the default folder for the instance (although the same cannot...
17 Mar 2017 by OriginalGriff
The way I do it is here: Backing up an SQL Database in C#[^] - and I normally get the access violation message the other way round, when I try to save the backup. It's probably the same problem however - SQL doesn't run under your user ID, so the destination folder needs appropriate permissions...
17 Mar 2017 by Andy Lanng
Oh for Pete's sake!I omitted the filename from the relocate paths >_
1 Mar 2014 by anik butt
Hey Guys,I have a parent class Fruits and two nested classes like Apple and Orange.This relationship is called inheritance.but can anyone plz tell me if i want to design table structure in the database.what would be that relationship called and how can i design/relate tables from that schema...