Transact-SQL (T-SQL) is a dialect of SQL used by Microsoft SQL Server and SAP's Sybase.

learn more… | top users | synonyms

3
votes
2answers
147 views

sql querying for a pattern

I was hoping someone could steer me in the right direction with this one. I have a table that has student grades. Create Table StudentGrades ( StudentID references Student(StudentID) int not null, ...
2
votes
1answer
23 views

How to group list of start times by a category?

I have a list people and when they started occupied various rooms in the building. Like so: IF OBJECT_ID('tempdb..#RoomAssignments') IS NOT NULL DROP TABLE #RoomAssignments; CREATE TABLE ...
1
vote
2answers
30 views

Applying Quotes Across Multiple Lines

In SQL Server Management Studio you can use the shortcut CTRL + K > C or CTRL + K > U to comment/uncomment lines in bulk. Is there a similar keyboard function that applies single quotes across ...
1
vote
2answers
17 views

How can I map a login to a database using T-SQL (not SSMS)

I'm writing a program that requires me to assign all permissions and everything in code. I have gotten stuck in this part: I just want to do the equivalent of clicking the little box under "Map" ...
1
vote
1answer
25 views

Restore Database SET SINGLE_USER

I am in the process of writing a restore database script. I want to be able to connect as sa and run the restore script. When I run SET SINGLE_USER does this mean that my login is the only user ...
1
vote
3answers
38 views

Script to drop all databases except one not working

I'm trying to drop all databases but one on my test server. For this, I'm using the below script but it gives error: EXEC sp_MSforeachdb ' USE [?] IF (DB_ID(''?'') > 4 AND DB_NAME()!=''ABC'') ...
2
votes
1answer
24 views

Implications of setting READ_Write

I am looking to update several users on READ_ONLY databases. As the databases are used 24/7 globally, and maintenance windows have just past, I would like to do this during a low-activity moment (to ...
0
votes
1answer
27 views

What is the most efficient way to concat strings in declared table

I have this code: DECLARE @MyTableAS TABLE ( [Month] INT, Salary INT ); INSERT INTO @MyTable VALUES (1,2000), (1,3100); SELECT [Month], Salary FROM @MyTable; Output: I want to concat the ...
1
vote
3answers
64 views

Excluding particular words from a string on a WHERE clause

I have a table that stores invoices and I'm trying to get stats out of it, unfortunately the table is poorly build and some crucial information is all mixed up on a nvarchar field, information such as ...
1
vote
1answer
49 views

No value to update but still an TABLE UPDATE Operator

I see this type of code a lot in my databases IF EXISTS(SELECT 1 FROM sample WHERE ID=@id) BEGIN UPDATE sample SET name='cat' WHERE id=@id; END So from my primary analysis it does 2 scan in ...
-3
votes
1answer
31 views

SQL Server 2012 Express Database Backup Script [closed]

Just a quick one. I want to do a full weekly backup of my SQL Server 2012 Express database. I have created a SQL script and batch file to automatically do a full backup of my database each week and ...
0
votes
1answer
25 views

Enforce a column as unique based on another column value

I want to make a column unique, but only if a different column is a specific value. Consider the following table: CREATE TABLE [SampleTable] ( [Id] INTEGER NOT NULL IDENTITY(1,1) ...
0
votes
1answer
18 views

DateDiff Returning Dates and Not Integer Values

I've added a [DAYS_FROM_TODAY] column to my table to calculate the number of days between today's date and the date a check was written for each record in that table. I used the following code to ...
1
vote
1answer
54 views

SQL Server : Job not reconnecting to restarted Linked Server

The problem To keep two tables across two servers in sync, we have a trigger that adds a change to a MergeTable. Every so often, a merging job runs on SQL Server to push the changes to the Progress ...
2
votes
2answers
102 views

Updating indexes and stats script

I am having the following errors with the script below Msg 102, Level 15, State 1, Line 44 Incorrect syntax near '?'. Msg 319, Level 15, State 1, Line 47 Incorrect syntax near the keyword ...
3
votes
1answer
62 views

How to check the timezone for a given datetime?

A database / table I'm working it saves all its date values as datetime (without a timezone). How can I find out which timezone that date was in? For instance, the Central European Summer Time (+02) ...
0
votes
1answer
37 views

Converting date string to SQL DATETIME - hopefully without a udf

I am taking an Excel file that has dates in different formats but one of these formats is giving me some grief when I try converting it or casting it to a SQL DATETIME. For example: Thu Oct 16 ...
1
vote
1answer
39 views

Read transaction log records

I am reading Remus Rusanu article on tlog.In that article he demoed on how to read log payload by using dbcc page option .My question is ,is there a way to read logrecord output of fn_dblog(null,null) ...
1
vote
1answer
53 views

A query for merging date intervals

I have a simple table with 3 columns: (cid, from, to) -> (int, datetime, datetime) The difference between dateFrom and dateTo should be >= 1 month. And unfortunately i have some corrupt data ...
1
vote
2answers
65 views

Query for orders that contain a product without using sub-query

Order ----- OrderId OrderDetail ----------- OrderDetailId OrderId ProductId How do I write a query that returns all orders that contain a specific product without using a sub-query? I don't want ...
8
votes
1answer
204 views

statistics are up to date, but estimate is incorrect

When I do dbcc show_statistics ('Reports_Documents', PK_Reports_Documents) I get the following result for Report ID 18698: For this query: SELECT * FROM Reports_Documents WHERE ReportID = 18698 ...
0
votes
0answers
40 views

Using loops inside Openrowset

I'm trying to execute a query across around 200 servers using openrowset function. This function needs to execute in a loop - the query is sucessfull in SQL Server 2012 environments, but failing in ...
4
votes
2answers
311 views

Truncating table without using Alter Table permission

So my DBA don't want developers to give Alter table permission. Now one of the procedure that we created requires to Truncate tables (since apparently delete only removes records, but truncate frees ...
0
votes
0answers
49 views

TSQL LAG equivalent

I am trying to understand how lag works, by converting the following code back to using self-join sql code without using lag. https://msdn.microsoft.com/en-us/library/hh231256.aspx USE ...
3
votes
3answers
82 views

I would like to get all values greater than 80, rank, then group in order to get a count of threshold breaches

I have the following basic dataset in MS SQL Server 2008R2: create table #temptable ( Source varchar(255), PollTime datetime, Value numeric(20,2) ) insert into #temptable( Source, ...
2
votes
1answer
155 views

T-SQL CTE Compare previous non-NULL and current row to filter out by difference value

My sample database (in fact a CTE statement data) looks like this: eventdate val 2012-03-23 3965 2012-03-26 3979 2012-03-27 3974 2012-03-28 3965 2012-03-29 3967 2012-03-30 3959 2012-04-02 ...
1
vote
3answers
317 views

How to create a SQL trigger to execute a stored procedure when a table is updated

i need some help with creating a trigger to run a qf.stored_procedure when a qf.table is created. AT the moment, i have a job t run the stored procedure every 15 minutes but changing that is not an ...
2
votes
1answer
84 views

Optimise select distinct from large table

I have a table that contains 320,071,712 number of records, the report that I am currently working on can filter the records by date, after which the number of records come down to 145,878,852. The ...
4
votes
1answer
50 views

Null Values in a CASE statement

I am playing around with some stuff in SSMS to learn a little more as I study for my 70-461 exam and I came across a little hangup. I am trying to create a table to play around with so I don't have to ...
-4
votes
1answer
46 views

Who is depends on specific column? [closed]

I want to alter column table from varchar X to Y. And for that I need to know who is depend on this column . Any suggestion?
1
vote
1answer
40 views

Select all most recent records

I have this two tables (and their main fields): Target: Message: Id IdMessage Id IdMain IdReply DatePosted ================ ...
0
votes
3answers
126 views

A more efficient way to write multiple CASE statements [closed]

SELECT CASE WHEN ( Table.COLUMN1) IS NOT NULL THEN 1 ELSE 0 END, CASE WHEN ( CASE WHEN ( Table.COLUMN1) IS NOT NULL AND ( Table.COLUMN2) IS NOT NULL THEN CASE WHEN ( Table.COLUMN1) - ( ...
1
vote
2answers
75 views

SQL Server query

All machines should have three groups(grp1,grp2,grp3) but some have two groups and some might have all three and some might have 1 or zero. I have data like this, I have two columns: MachineName ...
0
votes
2answers
36 views

How can I move backups location?

I have a seemingly easy question. How can I move a xxx.bak file to another location with T-sql? I have a job that takes a copy from database a to c:mycopy/copy1/a.bak and I want to create a step that ...
2
votes
1answer
73 views

T-SQL query to find backup folder for specific maintenance plan

I want to check check if backup plans are set up correctly and need to query different servers, mostly SQL Server 2008, but also 2012. Is there any way to query the maintenance plans for databases, ...
0
votes
0answers
23 views

Adding lot of new role assignment on different folders

On our local SSRS we are currently adding a big quantity of different users on different folders. The usual steps are like the ones detailed here SQL Server Reporting Services 2012 Permissions. Is ...
-1
votes
1answer
123 views

use variable as column name in where clause in sql

I want to use a variable as column name in my SQL query. Problem: I can not use dynamic SQL as the SQL query that I have is inside of a user defined inline table function. What are other possible ...
2
votes
1answer
79 views

SET CONTEXT_INFO for tracking specific SQL requests

I've got a problem where I'm seeing some very strange lock waits, with the process at the top of the lock wait tree in the 'sleeping' 'AWAITING COMMAND' state. I can see the machine name and ...
2
votes
1answer
61 views

Stored procedure with dynamic sql. Is it isolation safe by default?

I would appreciate confirmation on the answer I found digging through T-SQL's documentation. I have a stored procedure that references a view twice. Once in the procedure and then a second time when ...
0
votes
1answer
52 views

How to get best mark for each Student [closed]

I can't find a solution although it should be easy one. I have some students and all I need is to get the highest mark of each one in Math. TableName: Students. Columns: Name Mark John 90 John 84 ...
3
votes
1answer
223 views

Execution Plans Differ for the Same SQL Statement

As a background to this question the details can be found at this link. In a nutshell: I have 2 SQL statements that are almost identical except for the RIGHT table. The LEFT JOIN is the same and the ...
0
votes
0answers
38 views

Issues with Optimizing TSQL Script

I have a temp table that has a SecurityCode column. This SecurityCode column gets updated based off value from a CrossReference table. The value selected from the CrossReference table depends on how ...
0
votes
1answer
53 views

SQL weight multiplication

Hi all i have two columns in a table : +--------------------+----------------+ | Units/Pk | PackWeight/Vol | +--------------------+----------------+ | 1.0000000000000000 | 150g | ...
1
vote
1answer
81 views

Table size is not changed after new column is added

I am trying to check how the table size is going to be increased after adding new column with default values. I use the following default values: NULL, ''(empty string) and some text(some random ...
3
votes
0answers
72 views

How to format T-SQL identifiers in camel case

A number of tools exist which are designed to facilitate formatting the T-SQL in an inherited script or stored procedure to match one's personal preferences. One feature I would like to see in such ...
0
votes
1answer
43 views

Numeric Latitude & Longitude values are rounded up when querying SQL Server Database

Developing an application that is using Google Maps. Lagitude and Longitude values are stored in the table as the correct value. However when they are pulled into a view the value is rounded to the ...
0
votes
0answers
49 views

delete millions of rows from multiple tables

Hi we have to delete between 40 and 55% of records from several tables that have between 40 million and 100 million rows. Is it better to copy the rows we want to keep to a new table, drop the source ...
0
votes
1answer
68 views

How to increase the performance of this 3 minute reporting query

We have a table MyTable with about 10.000.000 records which contains a record of all transactions processed in our application. This table has the user Owner who did the transaction, the date ...
4
votes
2answers
113 views

How to change default database to all logins?

I'm bit new to SQL Server and I'm trying to script out Microsoft SQL Server (2005-2014) post installation activities and I got bit stuck on altering logins. Corporate policy states that none login ...
0
votes
1answer
44 views

Improving lots of Left Joins ( SQL Server 2008 - procedure )

This query is running with 8 minutes to complete. I'm trying to help the programmer with this task. I've created indexes and stats, update_stats and rebuild indexes but none of this is helping us. ...