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

learn more… | top users | synonyms (1)

2
votes
3answers
267 views

Student who got MAX marks in subject

I am facing one issue in getting student name who scored MAX marks in each subject. Here are my tables below First one is Student table having STUD_ID , STUD_NAME & Second one is MARKS ...
1
vote
1answer
45 views

storing as smallint, querying as int

A multi-billion-row fact table in our database has 10 measures stored as int columns. The value ranges for some of these columns won't ever be above the +/-32K range of a smallint. To save I/O, we're ...
1
vote
1answer
195 views

SQL Server stored procedure producing data related to months between two dates [duplicate]

I'm stuck on the following problem. I have a start range date and end range date calculated by a query and I have three columns also produced by another query, the outcome of the last query is: ...
0
votes
1answer
23 views

Put in the wrong data type for pk, cannot change because it is FK for another table [closed]

I'm trying to change the PK Department.DeptId to char(8), however it is an FK in employee. Doing two alters in 1 query throws an error for the first statement. Changing it in the edit window does the ...
0
votes
0answers
43 views

Recovered database files can't be attached

I have recovered my hard drive with my databases mdf and ldf files. When I want to attach them I get a 9004 error: Error: 9004, Severity: 21, State: 1. An error occurred while processing the log ...
3
votes
3answers
179 views

Update Table from SP in SSIS

I know there are similar questions to this one, but I could not find one that answered my question. Inside my current SSIS package... I have a dataflow task which... Takes output from a stored ...
2
votes
1answer
117 views

How can I combine two queries

I would like to combine these queries: UPDATE T1 SET Opening_date = T2.Opening_date FROM FactTransaction T1 INNER JOIN DimStore T2 ON T1.cod_Store = T2.Cod_StoreKey and UPDATE FactTransaction SET ...
1
vote
2answers
64 views

SQL Server 2008 having issues with HAVING clause

I have a question regarding a report I am currently writing. I need this query to only show me line items that have < -5 as mins_elapse Here is the code. I have left out the FROM clause to ...
2
votes
3answers
50 views

SQL Server: How to add a full join to two tables but have matches line up?

I am working with a system that has two databases. One for the ERP system and one for the website. Both DB's have tables for alternate codes. I am trying to write a query that will show me differences ...
11
votes
2answers
281 views

Why do SQL Server row estimates change when I add a join hint?

I have a query that joins a few tables and performs pretty badly - row estimates are way (a 1000 times) off and Nested Loops join is chosen, resulting in multiple table scans. The shape of the query ...
7
votes
2answers
239 views

When running a script with several commands, how to find out where we're at?

I have some processes that require different steps to be taken before they start. For example: Disable check constraint on foreign key: select 'alter table '+fk.table_schema+'.'+fk.table_name +' ...
0
votes
0answers
18 views

How to identify a process that has been cancelled?

How can you identify a process that has been cancelled? for example: I was running this dynamic sql - via a linked server: declare @sql nvarchar(max) declare @i int declare @z int DECLARE @vCrlf ...
1
vote
1answer
64 views

dynamically creating query in a loop [closed]

I"m looping through a table trying to create a dynamic sql query. It appears to work fine except when I'm concatenating results to make the actual statement. Psudo code follows WHILE (Data is in the ...
0
votes
2answers
116 views

what is the quickest way to delete duplicate rows?

I need to delete duplicate rows from a large table. what is the best way to achieve that? currently I use this algorithm: declare @t table ([key] int ) insert into @t select 1 insert into @t ...
8
votes
3answers
1k views

Filtered index only used when the filtered part is in the JOIN not the WHERE

I've created the filtered index below however when I run the 2 queries further down this index only gets used for a seek in the first example that has the END_DTTM in the JOIN rather than the where ...
-2
votes
1answer
38 views

Last date SQL Server query required

Scenario: I am writing a cash management system and want to put some date columns for getting date info / history. Actually there are two columns for date in same table at this moment. Voucher Date ...
1
vote
1answer
61 views

SQL Server lock_escalation flag on ALTER TABLE — can I really restructure without a table lock?

SQL Server 2014 Standard Edition In my situation, I have a huge table (100 million+ rows), and need to: add column to it set default value in that column I see in ...
11
votes
2answers
312 views

Unable to mirror a database SQL Server 2012

When trying to mirror a database using the following command ALTER AVAILABILITY GROUP SQLAlwaysonGroup ADD DATABASE test0916aj8CJ I get the following error Msg 1475, Level 16, State 105, Line 1 ...
5
votes
1answer
145 views

Why does this query not use the index that exists on SURNAME?

There is an index on SURNAME in the PATIENTS table, we run the following query but the index doesn't get used. DECLARE @SURNAME VARCHAR(30) = 'test' SELECT SURNAME FROM PATIENTS AS PAT WHERE ...
9
votes
1answer
561 views

Are explicit transactions needed in this while loop?

SQL Server 2014: We have a very large (100million row) table, and we need to update a couple of fields on it. For log shipping, etc, we also, obviously, want to keep it to bite-size transactions. ...
3
votes
1answer
52 views

Query to list “last backup time” listing wrong times ( SQL Server 2008 R2 )

I use this query to list last backup dates of our databases: SELECT SDB.NAME AS DATABASENAME, COALESCE(CONVERT(VARCHAR(12), MAX(BUS.BACKUP_FINISH_DATE), 101),'-') AS LASTBACKUPTIME FROM ...
7
votes
3answers
256 views

sql server: updating fields on huge table in small chunks: how to get progress/status?

We have a very large (100million row) table, and we need to update a couple of fields on it. For log shipping, etc, we also, obviously, want to keep it to bite-size transactions. Will the below do ...
1
vote
0answers
26 views

How to parse and display row data as Column

I'm trying to display the row data from tbl_cte as a column. The result of column1 is alphanumeric e.g : "Data1.2.3". I need to parse it and display the "Data" as the name and "1.2.3" as the version ...
1
vote
1answer
70 views

How to remove the WITH ENCRYPTION from the code of the procedure - via T-SQL [duplicate]

I have many procedures that I use the option WITH ENCRYPTION when I create them. You can see this on the picture below, as an example: the problem with this is that when I want to save my previous ...
1
vote
1answer
297 views

How to add/update a column with an incremented value and reset said value based on another column in SQL

I am stumped, I have searched and researched until my browser tabs no longer show the close button ("X") until you hover over them. I tried rewriting the search term over and over but I guess I do not ...
8
votes
1answer
96 views

How can I get the hierarchical values from the below query?

I have a table named Category which has a column named CategoryID. There is a referencing column in the same table called fParentCategoryID. I need to get all the category IDs and their subcategory ...
2
votes
1answer
58 views

Stored procedure suddenly very slow, updating statistics not helping

Like the title says, I have a stored procedure that suddenly started running very slowly. Previously it took about 5 seconds to execute, now it is taking seven minutes or more. This seems to have ...
3
votes
1answer
71 views

Find the most recent row where no exact match on date is found

I am trying to write a query that tries to extract the value of the exchange rate where: Query date = the exchange date; and Query currency = the specified currency If it does not contain a ...
6
votes
1answer
67 views

Why does assigning FOR XML to an XML variable warn about CONVERT_IMPLICIT(XML)?

SET STATISTICS XML ON; DECLARE @x XML = (SELECT 'hi' "@id" FOR XML PATH ('this'), root ('xml')); Type conversion in expression (CONVERT_IMPLICIT(xml,[Expr1001],0)) may affect ...
8
votes
3answers
206 views

What is lost when I create a Foreign Key using `WITH NOCHECK`?

I know that if I do an EXISTS() call on a FK lookup value, then, if that FK constraint is trusted, the result is immediate. And if it is not trusted (like when I create the FK using WITH NOCHECK) ...
40
votes
5answers
1k views

Date range rolling sum using window functions

I need to calculate a rolling sum over a date range. To illustrate, using the AdventureWorks sample database, the following hypothetical syntax would do exactly what I need: SELECT TH.ProductID, ...
4
votes
2answers
745 views

Listing SQL Server instance startup parameters

I have a server I have just restarted and verified which trace flag are active using DBCC TRACESTATUS: Trace Flag : 3688 Function: Removes messages to errorlog about traces started and stopped ...
2
votes
1answer
96 views

How to map a drive in a SQL Server script

I am trying to execute below script to Network a Drive use master go exec sp_configure 'show advanced options', 1; go reconfigure go exec sp_configure 'xp_cmdshell',1; go reconfigure go EXEC ...
5
votes
3answers
136 views

Charindex, Getting specific data from a string

Hello I am very new to charindex and have tried to create a query that would extract my needed information but am running into an error. I searched for similar problems on stackexchange as well as a ...
4
votes
0answers
91 views

How can we improve this PIVOT operation? ( SQL Server 2008 R2 )

We have this query, that runs in 1:10. We need to improve this. This is just a test query, but we will implement this upgrade on our real query. select top 100 * from ( select codCliente ...
-1
votes
3answers
82 views

Joins in Stored Procedure

Below is my code, which returns billable and non billable total hours for their projects. I want to show in single row, but i am getting two result sets like below. DECLARE @UserName NVARCHAR(50); ...
2
votes
1answer
71 views

One SQL different Results by using SQLOLEDB or MSDASQL

I'm using VB6 with SQLOLEDB and MSDASQL. By switching the provider I notice that I'm getting different results with one query. My query checks some server settings and executes one of two BACKUP ...
0
votes
1answer
147 views

Is there a way to run this query in all databases ? ( SQL Server 2008 R2 )

How can I use this query for each database? I can easily use sp_msforeachdb but it breaks the results for every database. So I tried to insert the results in a temp table, but it's giving me syntax ...
-2
votes
1answer
53 views

Business Date and Route Sequence

+-------------------------------------------------------------------+ |Route |Sequence| Planned Time | Business Date | ...
0
votes
2answers
66 views

How to Create Insert Statement from Table Data using sp_export_data without Id?

How to Create Insert Statement from Table Data using sp_export_data without the Id? I have the following statements and want to omit the Identity. How would I accomplish this? This is how I'm ...
2
votes
3answers
48 views

SQL Server 2012 window function

I've the following table which holds status of jobs in a history table. JobHistory jobOrderId | dateAdded | Status -----------|-------------------------|------- 4909 | 2015-08-26 ...
0
votes
1answer
57 views

Run Query Against All DB's on Server

I am trying to run this against all the DB's on my server and not just on "TEST_1". Is there a simple way to do this? Ideally the select would also return the DB name. use TEST_1 go declare ...
1
vote
1answer
87 views

How to measure the performance improvement that NUMA brings?

I am testing how one of our stored procedure is working on SQL Server Standard vs SQL Server Enterprise editions. I have created two virtual machines and install a SQL Server(SQL Server 2014) and ...
3
votes
2answers
204 views

Using sp_getapplock to implement a queue. Is it correct? Is there a better way?

I've been reading a series of posts by Paul White about SQL Server Isolation Levels and came across a phrase: To emphasise the point, pseudo-constraints written in T-SQL have to perform ...
1
vote
1answer
15 views

Query Relating Rows W/O A Corresponding Value

I have a table setup like this: ID Code DateActive DateInactive statusCode 15 20090413 null A 15 null 20090416 I 15 20100101 ...
2
votes
0answers
133 views

How do I provide a failsafe for retrieval of data from excel to SQL

So say there is a process in place for importing data from excel spreadsheet to SQL using SSIS. And there are two tables, one with new data and one with data from its previous run. I sometimes have ...
4
votes
1answer
481 views

Select when group by contains more than one row with the same value?

I am trying to write a query that returns one row from table A whenever a column in joined table B contains multiple distinct values for a single matching row in table A. (A -> B is a 1 -> many ...
4
votes
3answers
118 views

Return even empty groups when grouping by date

I have the following query: SELECT DISTINCT COUNT(CD_BarCode) ,CD_Carrier ,SUBSTRING(CONVERT(VARCHAR,DT_Arriving,103),1,11) Date FROM TB_AGIL WHERE ...
3
votes
2answers
101 views

How to wait for SQL Server replication reinitialization via TSQL

We use transaction and push replication. Every night after the data import 2 replication targets are initialized with the following commands. USE [dbImport] -- Execute at the Publisher to ...
2
votes
2answers
114 views

Error 4108: Windowed functions can only appear in the SELECT or ORDER BY clauses

The error in the title is produced when add the second condition in my where clause. I understand the error, have tried using subqueries as seen in other posts to fix this but no luck. Does anyone ...