Questions tagged [t-sql]

T-SQL (Transact Structured Query Language) is the extension of SQL functionality supported by Sybase ASE and Microsoft SQL Server. Do not use this tag for MySQL, PostgreSql, Oracle(Pl/SQL) related queries. Please note that SQL code which is being written using LINQ will not also be the part of this tag. This tag specifically created for advanced SQL programming using Microsoft SQL Server.

Filter by
Sorted by
Tagged with
0 votes
0 answers
20 views

SQL Server Agent job runs successfully, but only for 1 second and doesn't actually do anything. Runs fine manually

I have a SQL Server Agent Job that runs two separate stored procedures in two steps. It's scheduled, and the scheduled run technically finishes successfully, but the run time is only 1 second and it ...
B.Scar's user avatar
  • 47
-1 votes
0 answers
31 views

Average function on a group by shows wrong number for TSQL query

I have used the below query: select format(CreatedOn, 'yyyy', 'fa') as Date, sum((elg_Behaviour-861239999)) as Sum, count(*) as Count, AVG((elg_Behaviour-861239999)) as Average ...
Pey's user avatar
  • 9
-5 votes
0 answers
57 views

Is there is a library or a way to convert T-SQL query to mySQL? [closed]

I'm working on writing a converter/generic method to convert T-SQL queries to mySQL. From what I understand 100% conversion is not possible, I'm looking into either writing a regex or maybe look into ...
ICoder's user avatar
  • 155
0 votes
2 answers
75 views

Query to return a row for each separated value in column

I have some SQL log data like this: date user actions 2023-01-01 dave changed; added:apple 2023-01-02 gail changed; removed:apple 2023-01-03 mick changed; added:apple; removed:banana; added:cherry;...
jim birch's user avatar
  • 423
1 vote
2 answers
49 views

Why VARCHAR data sorted as if there was a space appended on the end

Using SQL Server 2017, I encountered a query that was sorting on a VARCHAR column returning results in a different order than I expected, namely a string followed by a tab came before just the bare ...
user221592's user avatar
2 votes
2 answers
77 views

How to write a WHERE clause with row_number in T-SQL?

WITH CTE AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY opened_at) RN FROM table ) SELECT column1, column2 FROM CTE WHERE RN = 2 If there is no RN = 2, ...
dexter_walking's user avatar
1 vote
2 answers
67 views

How do I get the sum of a count and group by a column

Getting stuck with a query getting the sum of counts. I have a situation where I have to get every department and sum up all employee tasks Currently my output is as follows Department Total Tasks ...
Donald Dax's user avatar
0 votes
2 answers
121 views

Combine multiple text injection

I have a table that has these records on SQL Server RepID iBegin iEnd RepText 1 10 17 This is a profile of ... Moreover Toyota has been ... such as Mazda also ... 1 38 ...
asmgx's user avatar
  • 7,376
-1 votes
1 answer
86 views

T-SQL DENSE RANK with concat

DECLARE -- Comment out this line for Procedure @ordOrderNo INT = 2716, @ordCommtAbrv VARCHAR(30), @salesOrderNo VARCHAR(10), @trailingIdent VARCHAR(1) = 'S'; -- Drop the ...
Ricky Chau's user avatar
0 votes
1 answer
35 views

How in T-SQL can I set the next N isAudits to true every X records?

I'm trying to figure out, either using T-SQL or C# / Entity Framework, how I can mark a batch of N records true every X records that get created. So here's an example of what the data would be if N = ...
thetimmer's user avatar
  • 188
0 votes
2 answers
62 views

Sort on T-SQL unioned query with CTE

I need to do a sort on a T-SQL unioned query. No matter how I write the query, I'm getting a syntax error once I introduce the ORDER BY clause. Incorrect syntax near the keyword 'order' T-SQL query ...
Rick's user avatar
  • 57
0 votes
1 answer
34 views

How to Handle multiple duplicate records in one column by populating the values in second column with same name?

enter image description here In the table , I have multiple records like of the movie name Adalat and the genre for 3 is different and one is null. I want to populate the empty place with the Genre of ...
SUMANDEEP's user avatar
-2 votes
1 answer
35 views

why does my combobox show duplicate values a number of time the fields in the table? [closed]

cbo_bat_prod_bat.Items.Clear() conn.Close() conn.Open() comm = New SqlCommand("SELECT distinct (production.batch_no) as ...
Nsubuga Tonny's user avatar
0 votes
1 answer
38 views

Concatenate Strings to make column alias

I am trying to make a column alias that concatenates strings (one coming from a parameter). I'm running the same query with different values on the parameter to generate my report to send out, and I ...
scotscotmcc's user avatar
  • 2,741
-1 votes
0 answers
29 views

For a SQL Server page, is there a distinction between being "in memory" and "in the buffer pool"? [migrated]

The following excerpt is in Chapter 10 of T-SQL Querying by Itzik Ben-Gan. He is listing the benefits of In-Memory OLTP tables over traditional pages. You can also dispense with the considerable ...
J. Mini's user avatar
  • 2,008
0 votes
0 answers
43 views

Can you create a "virtual index" that contains the aggregate of a number of common table expressions in sql? [closed]

We have a structural table, the data within which has a parent / child relationship. The table doesn't use the Hierarchical data type, just old school parent / child relationship. The structure holds ...
Storm's user avatar
  • 1,864
1 vote
1 answer
46 views

Can a page be anything other than allocated or deallocated?

The documentation for sp_WhoIsActive states The most confusing of these columns are those related to tempdb. Each of the columns reports a number of 8 KB pages. The [tempdb_allocations] column is ...
J. Mini's user avatar
  • 2,008
0 votes
1 answer
38 views

Is there a transaction isolation level equivalent to the READCOMMITTEDLOCK table hint?

The documentation makes it clear that you can use the READCOMMITTEDLOCK table hint to get the default SET TRANSACTION ISOLATION LEVEL READ COMMITTED behaviour when the non-default ...
J. Mini's user avatar
  • 2,008
0 votes
1 answer
49 views

Get element with newest date

I'm trying to get the element with the newest date from various JSON arrays. But I can't get it to work. It returns all the elements from the arrays. I have tried several things with MAX, TOP(1), ...
OJ Slott's user avatar
-4 votes
1 answer
43 views

Send the table data to an email using DB Send mail in SQL Server

I am trying to send the table data which comprises of 2 columns Status and Count through email. And I need to achieve this from stored procedure with DB send mail. I wrote the below code, but the ...
Aparanjit's user avatar
0 votes
1 answer
64 views

Efficient LEFT JOIN on two tables

I am trying to join multiple table in SQL Server and keep the performance fast. CREATE TABLE #tmpRecords ( recordID INT NOT NULL, filter1ID INT NOT NULL, filter2ID INT NOT NULL, ...
Stormdust's user avatar
-2 votes
1 answer
39 views

How to loop through a list of variables to pass into stored procedure parameters in T-SQL [closed]

I have a stored procedure that takes in two parameters: a beginning and an end date in the format YYYYMM. The format of this field (in the underlying table is simply int). The stored procedure ...
Shaye's user avatar
  • 195
-2 votes
0 answers
45 views

Limitations on SQL queries through MS Access/VBA? [closed]

I've written a quite complex SQL query (not complex as in advanced, complex as in many components) which works fine when run through Python or Azure DB Studio for example. However, when I try to ...
AlexSahlin's user avatar
1 vote
2 answers
99 views

How do I merge / decouple times like this in SQL?

I have downtime data with 2 machine IDs (333 & 334). The downtime comes in separately, but I need to transform it such that: When both machines are down, the duration counts towards 100% of the ...
Andrew's user avatar
  • 447
-2 votes
1 answer
57 views

Convert an .sql file from a SQLBase server in to SSMS

I am attempting to convert a .sql file from a SQLBase server in to SSMS but am having trouble doing so. The file contains queries that will create a database with 600+ tables and their data. The ...
jeremiahgarrett's user avatar
-1 votes
0 answers
21 views

Turkish characters are not inserted correctly [duplicate]

I have a table with (lockey, trvalue) columns. I just realized that when I insert into the database using, INSERT into myTable (lockey, trvalue) values ('test', 'ııııığçIĞÇ'); the data is inserted as (...
Toprak's user avatar
  • 1
0 votes
2 answers
72 views

Concatenate the 'EmployeeId' fields with separated by a comma

-- Create a sample table `CREATE TABLE #YourTable ( RowID INT PRIMARY KEY, column1 VARCHAR(255), column2 VARCHAR(255), column3 VARCHAR(255), AssociatedRows VARCHAR(MAX) );` -- ...
Dev Sils's user avatar
-2 votes
0 answers
23 views

Update EmployeeDuplicates field with concatenated employeenumber where address or name or ssn is matching

CREATE TABLE #Employee ( EmployeeID INT PRIMARY KEY, EmployeeNumber VARCHAR(10), EmployeeName VARCHAR(255), EmployeeAddressClean VARCHAR(255), EmployeeCityClean VARCHAR(255), ...
Dev Sils's user avatar
0 votes
1 answer
27 views

Merge parquet files into external tables synapse

I extract data daily from a data source and store it in Parquet, then I created an external table in synapse. I want to constantly update the external table with data that is been extracted daily. I ...
Mr_Unchained's user avatar
1 vote
1 answer
62 views

Get a list of @Parameters in a T-SQL script with its datatype

From a T-SQL script like this: Select Proveedor.RazonSocial, Articulo.ArticuloId As Código, Articulo.Descripcion As Descripción From Articulo Inner Join Suministrador On (Articulo....
MartinHT's user avatar
  • 301
0 votes
2 answers
43 views

On raising error cancel all sub stored procedures inside of the main stored procedure [duplicate]

I have a main stored procedure in a SQL Server database. Inside this main procedure, I've called some other procedures, and within some of those procedures, I've called additional stored procedures. I ...
Damoon Salatian's user avatar
0 votes
1 answer
25 views

MSSQL Query Start and End Date where dates sequential then next row [duplicate]

I have a mssql table such as the below Calendar ID int CalendarDate datetime Available bit Booked bit Example Records are 1 01/09/2023 1 0 2 02/09/2023 1 0 3 03/09/2023 1 0 4 04/09/2023 1 0 5 ...
matt's user avatar
  • 99
0 votes
1 answer
54 views

How to check if only specified column was updated?

I try to check in a trigger, if only specific column was updated. When only this column, I want to exit the trigger immediataly. Here is my Code: DECLARE @colId int; SET @colId = COLUMNPROPERTY(...
BennoDual's user avatar
  • 5,865
0 votes
0 answers
50 views

How to use SQL function output in a cte in Serverless SQL?

I have a function which outputs a table, called fnDimDate(startDate, endDate). I need to use this table in further data transformations. I created a CTE like this: WITH ...
Jem's user avatar
  • 567
-1 votes
0 answers
35 views

Msg 240, Level 16, State 1, Line 159 Types don't match between the anchor and the recursive part [duplicate]

I am trying to extract a Quantity BOM Explosion report and i'm getting the data type error for my CTE subquery. Error: Msg 240, Level 16, State 1, Line 159 Types don't match between the anchor and ...
Ninna's user avatar
  • 9
1 vote
1 answer
21 views

SQL Server Transactional Replication with local Publisher/Distributor and Azure Subscription

Is is possible to have a Transactional Replication configured with local Publisher/Distributor and with Azure Subscription? I was thinking to create an Historical DB on Azure VM that replicates the ...
Paulky's user avatar
  • 11
0 votes
3 answers
86 views

Get first byte on an Integer

How can I get the first byte of an integer value in SQL Server? In C#, I can do it easily using the BitConverter: int x = 383; var firstByte = BitConverter.GetBytes(x)[0]; Console.WriteLine(x); // ...
Aan Dahliansyah's user avatar
0 votes
1 answer
47 views

How to join on a linking table?

I've created a stored procedure and in there I'm joining a couple tables: SELECT ... FROM [Place] AS [P] JOIN [Timezone] AS [TZ] ON [TZ].[TimezoneId] = [P].[TimezoneId] JOIN [Address] AS [A] ...
CodingIsFunYouShouldTryIt's user avatar
-1 votes
1 answer
51 views

Selecting count of records with different gender but same first name and last name

I have a table that looks like below unique_id first_name last_name gender 1 john smith M 2 kevin jones M 3 kevin jones F In this example, records with unique_ids #2 and #3 are the same person ...
pmh's user avatar
  • 59
0 votes
1 answer
50 views

Select IDs of lines where nvarchar column cannot convert into date

Let's make it super simple: 2 columns, id and textDate. For some of the lines, the textDate field will contains null, which is ok, sometimes it will contains something like '2017-06-24' which is also ...
Antoine Pelletier's user avatar
0 votes
0 answers
36 views

Can I set the default value with a subquery?

I am trying to set the default value for shipment_mst.co_num to be pulled from ssspj_shipment_mst.userfield2 . Everything I have seen, and tried gives me the error 'Subqueries are not allowed in this ...
Clay's user avatar
  • 1
-1 votes
0 answers
20 views

SQL query dynamic pivot - How to get this query working? [duplicate]

I have the below dynamic query where the source table will have two columns [Name], [Value]. How can I apply pivot to transform the values from [Name] into column headers and generate a single row? I ...
Jyina's user avatar
  • 2,538
0 votes
3 answers
49 views

Find row with closest value down

I have a shipping cost table with two dimensions: Zone and Weight. Zone is an exact value. Weight is a range where given value is lower inclusive one. That means that in the given example, the highest ...
Megrez7's user avatar
  • 1,425
-1 votes
0 answers
56 views

Avoiding circular references and not revisiting objects that have already been visited

I'm facing a challenge with SQL recursive common table expressions (CTE). I have a SQL query that uses a recursive CTE to retrieve dependencies for a given object. However, I want to ensure that I do ...
Shoaib Maroof's user avatar
0 votes
0 answers
36 views

Fastest Time for a Runner [duplicate]

I have a time trial application which times runners over various running routes. I have a table (TT_DTL) which has the following columns: RecordID - primary key TT_HDRID (fk) - this is linked to the ...
Adam Walker's user avatar
0 votes
1 answer
21 views

Not in aggregate function or group by clause but summing column in a window function

I'm getting the following error when trying to run the code below however usedslots is in a sum function. Column '#temp.UsedSlots' is invalid in the select list because it is not contained in either ...
Shadocvao's user avatar
0 votes
0 answers
35 views

T-SQL Parallel execution when using CREATE?

If I have a single T-SQL script that looks like this, and each table individually takes 10 minutes to write to the database, will the total script time be 10 mins or 20 mins? I.e. is parallel writing ...
Sachin's user avatar
  • 117
-1 votes
1 answer
52 views

Between conditions with dates has odd behavior

I have this T-SQL query in SSMS: DECLARE @TodaysDate datetime DECLARE @AsAtDate DATETIME SET @TodaysDate = GETDATE() PRINT (DATEPART(WEEKDAY, @TodaysDate)) IF DATEPART(WEEKDAY, @TodaysDate) = 2 ...
Prosy Arceno's user avatar
  • 2,606
0 votes
1 answer
53 views

Repeat a code block in a stored procedure without retyping

I have a block of code that I want to use over and over in a stored procedure. This block of code will set a number of variables to blank (''). I would like to do this without having to copy/paste the ...
Sabatino Ognibene's user avatar
0 votes
0 answers
47 views

How to find a specific business date

I have a client requesting an automated daily report that includes several month to date metrics. Normally I would use code like this to find start and end of month values: SELECT DATEADD(m, DATEDIFF(...
Greg's user avatar
  • 45

1
2 3 4 5
1455