Transact-SQL (TSQL) is the extended SQL dialect used in Microsoft SQL Server and Sybase. Please also tag with either [sql-server] or [sybase].

learn more… | top users | synonyms

15
votes
5answers
321 views

Winterbash 2014 “Red Shirt” Estimation

Some fellow code reviewers (hi @Janos!) have been inquiring about a SEDE query to allow to check progress of the Red Shirt "hat" progression. Try it here! Background Red Shirt cast 5 ...
7
votes
6answers
145 views

SQL Server: Select first value if exists, otherwise select default value

Given an instance of SQL Server, imagine there's a table named Configuration, which has three columns: ID, ...
13
votes
2answers
61 views

Bling Accounting - Badge summaries

A question was raised in chat (hi @malachi) about how you can count the number of badges of a given metal (bronze, silver, gold). This can be hard to do because the medal details are not stored in the ...
3
votes
2answers
45 views

Running validation procedures on a table

I am working on a project that has to parse through a text file and perform validations on certain fields in the file. Some of the validations are basic(i.e. data types), and other's are a little more ...
1
vote
1answer
28 views

Cluster date time values

I came up with this TSQL for SQL Server 2008: ...
3
votes
2answers
53 views

Calculating Standard Deviation using SQL

I have been reading a bit about statistics to improve the way I understand data. This is my attempt at calculating Standard Variance using data tables. I solved this simple question: This is the ...
4
votes
3answers
305 views

For a query over multiple databases, is it faster to do GROUP BY first or UNION first?

Having several databases with the same table, I need to group the union of the records. The xTables are stored in separate databases named by the year (this is by ...
21
votes
2answers
1k views

Calculate amount of mugs StackExchange should give away so I'll receive one

Description Calculate how many mugs StackExchange should give away(for graduation) to top reputed users on codereview.stackexchange.com so I'll also receive one. (output is divisible by 50). Code ...
11
votes
4answers
277 views

LW, MTD, STD, YTD Sales… all in line and looking pretty

That's Last Week, Month-to-Date, Season-to-Date, and Year-to-Date sales. I have a table-valued function for each one, that takes a date and returns all ...
3
votes
2answers
44 views

Extract last record inserted for each key identifier

I have a table with this schema ID, int primary key PathKey, string not null InsertDate, datetime not null Value, int not null In the table there are a ...
5
votes
1answer
48 views

Saving and updating records

I have made two SQL statements as I was unable to figure out how to solve my problem. One is called Product_GetID and the other ...
6
votes
2answers
149 views

Follow up to Top Active Answerers on Stack Exchange site

This is a follow up to Top Active Answerers on a Stack Exchange site Actual SEDE Query --> Top Active Answerers on site Do I have a good understanding of the ...
3
votes
2answers
273 views

Top Active Answerers on a Stack Exchange site

I created this query back in January to find the top active answerers on Code Review and thought that it might be a good idea to get other opinions on my SQL coding using a database that we can all ...
3
votes
1answer
51 views

Basic T-SQL to compare two same length strings

I've come up with the following T-SQL to compare similar same length strings. Example usage would be: OCR returns a value which is expected to be in the database. PATINDEX is used to check the ...
3
votes
1answer
76 views

Query for combining two SELECTs to get active users and 1 inactive user

What this query does: Gets multiple users with the first select in the union; those are the active users. But when a user is ...
2
votes
1answer
23 views

Optimizing sales report stored procedure

I need to optimize the following stored proc. Please let me know of any techniques or modifications that I can make to optimize this piece of code. The procedure is for a report that needs to run ...
4
votes
3answers
59 views

Retrieve Father and Child structure in a Database Table

I have a table with this schema: CREATE TABLE [td].[MyTable] ( [ID] [int] NOT NULL ,[FatherID] [int] NULL ) (Note: I have excluded all the columns not ...
4
votes
1answer
79 views

Unduplicated counts over various dimensions

I'm working with some data on college students, which has a unique key of SSN, Campus, ...
5
votes
1answer
60 views

SQL query with dynamic unpivot+pivot for cross product

In this Data Explorer query I am trying to do the following: For each tag: Compute sum of answer scores in this tag ("S") Compute count of answers in this tag ("A") For each tag class (Bronze, ...
20
votes
6answers
2k views

Average time to first answer

Just trying out my T-SQL foo. Wrote a script to get the average time (in seconds) to first answer for a specified language. ...
4
votes
2answers
132 views

Delete from multiple tables using temp table variable

I'm previewing the data I'm about to delete, but this SQL looks a little redundant. Is there a better way to write this? ...
6
votes
3answers
109 views

SQL Stored Procedure Get Distinct and Update

The idea is to show how many times a user (by EmployeeID) is in the TblTableList and then update the ...
6
votes
2answers
104 views

Put it in a bucket

You're running a jeans company. Your system is collecting detailed orders' data, but it's a bit archaic and it's storing the number of units ordered per size in a delimited string with 20 "fields", ...
6
votes
3answers
142 views

Sorting three Decimal values

I have been given three values. @lLength, @lWidth, @lHeight. I need to take these ...
5
votes
1answer
311 views

Dynamically filtering, sorting, and paging using a stored procedure

Is there a better way (I'm pretty sure there is) to create a stored procedure to do dynamic paging, filtering and sorting than the following code? ...
5
votes
2answers
79 views

Better way of calculating a time in a time zone from multiple dates in SQL?

I'm trying to calculate what time a certain time in a time zone is today, so I can schedule something to happen at that time in that time zone. I've got a table with what I have termed the Nominal ...
6
votes
4answers
123 views

SEDE-Query for Rep-Trivia

The code should be relatively self-explanatory. I was wondering how much rep the Top Voters on sites did "generate" on a site, in comparison to how much rep they "own". Therefore I created a little ...
6
votes
1answer
137 views

Count and group rows for six months prior

I've written the following query for SQL server: ...
4
votes
1answer
45 views

SEDE query to find users with exactly one post in a particular tag

I'm doing some research for a meta post on Gardening.SE (where I'm a pro tempore moderator). I'm using the Stack Exchange Data Explorer (SEDE) to find information about first time users who post ...
6
votes
2answers
104 views

Inefficient query actually more efficient?

I have two queries; one runs significantly faster than the other, but the faster one is the one that I would have bet money on to be less efficient. These are both being executed through a front end ...
6
votes
1answer
52 views

Aggregating Conditional Sums

I have recently forked/rewritten a SEDE query (here) that aims at figuring out where a site stands in terms of avid users and distribution of reputation scores, compared to a specific target (number ...
7
votes
3answers
146 views

Return the top 5 of each kind of record

I have this currently working code, but it's extremely slow. I'm talking almost an hour to execute, if it executes at all (our server isn't all that great to start with). Is there a better way to ...
15
votes
1answer
223 views

Calculating Lost Reputation

A discussion arose not long ago on the 2nd Monitor about how much reputation has been lost due to the reputation caps. There are a number of queries on the SEDE which try to address this: A Users ...
11
votes
3answers
169 views

SEDE Top Sponsors

I wanted to see the site's top sponsors - users that have paid bounties on questions that they didn't own. I started off with a bounty-related existing query, selected the details into a subquery, ...
4
votes
3answers
86 views

Remove duplication in SELECT statement

Say I have the following SQL: SELECT amount, amount*.1, (amount*1)+3, ((amount*1)+3)/2, (((amount*1)+3)/2)+37 FROM table Instead of ...
2
votes
1answer
120 views

Query too slow - Optimization

I am having an issue with the following query returning results a bit too slow and I suspect I am missing something basic. My initial guess is the 'CASE' statement is taking too long to process its ...
3
votes
2answers
149 views

SQL query clustered with repeated function calls

I have the following SQL query that computes for every date the week it falls in (a week begins on Sunday and ends on Saturday): ...
1
vote
2answers
190 views

Maintaining a total balance of debit/credit sales transactions

The overall intent is to consolidate individual sales transactions to total debits/credits summing up the totals by year and month--retaining a running balance from start to end. This code uses ...
1
vote
2answers
70 views

Store procedure timing out sometimes

Can someone please find out why this store procedure is timing out? ...
4
votes
2answers
829 views

Selecting the number of working days minus weekend days and UK bank holidays

I am fairly new to coding TSQL script and am looking for some second view on my script. The goal here is to to pull in some data and amongst that data to show a field with a counting the number of ...
1
vote
1answer
302 views

DRY cursors: preventing T-SQL's FETCH statement from being repeated

Please assume I've exhaustively tried to come up with a set-based solution to my T-SQL problem, and that I need to use a cursor. The following is the typical1 boilerplate for a T-SQL cursor: ...
4
votes
1answer
143 views

SQL Server 'Execute As'/Revert pattern in a 'Try/Catch' Block

I wish to ensure I am using the "best" pattern when using an Execute As/Revert from within a Try/Catch block on SQL Server 2012. The below code "seems" to behave correctly... Am I missing anything or ...
1
vote
2answers
112 views

How can I make this WHERE clause more readable?

Without changing the semantics and performance, how can I make this where clause more readable? ...
2
votes
1answer
123 views

How can I improve the following stored procedure?

I have created the following stored procedure which duplicates a record in a table and also all its related records in other tables however since I am a newbie to SQL I would appreciate it if someone ...
3
votes
1answer
4k views

Returning Key Values from Stored Procedures

I wonder which is better practice when I need to return the primary key value of a newly inserted record from a SQL stored procedure. Consider the following implementations: As Return Value ...
-1
votes
1answer
359 views

Using xp_cmdshell

Am I doing it fine?? Its only for setup not executed repeatedly ...
1
vote
0answers
162 views

T-SQL BFS center node of undirected graph [closed]

I am trying to answer this question by using a breadth-first search from each node of the graph represented by the tables mapSolarSystems and ...
0
votes
1answer
752 views

Daily, Weekly, Monthly Individual Tech time in task Repoert

I'm trying to create daily, monthly and weekly SQL Query report to our services time we spent int task and total billing time just want to see if I'm on right track ...
2
votes
1answer
918 views

Sql query to obtain totals and subtotals

I'm interested in knowing if there's a better/cleaner/more efficient way, to obtain totals and subtotals within a query, than my solution below. The query works fine but I'm just intrigued to know if ...
3
votes
1answer
217 views

Is it necessary to replace this cursor in SQL Server 2005?

The Problem I have a cursor that I am trying to replace (perhaps unnecessarily) in an attempt to clean up a stored procedure. Essentially what it is doing is counting each note for each member in a ...