SQL Server STUFF String Concat Slow - sql-server

Is there any alternative to the SQL Server STUFF function?
I am developing a Windows Service that loops over a database and does some data processing, but the step of fetching data is extremely slow.
I have these tables
Sensors table that define sensors config
Items table that records each item information from devices
Itemdata table that stores sensor values for each item row, so Itemdata table is linked to Sensors and Items tables
I need to select data from items with grouping itemsdata as col like this
1=5|2=6|
I use this T-SQL - it's working fine, but it's slow with more than 200,000 rows.
Without it, exec is extremely fast
With actual execution plan it take 99% in the stuff function:
I am using the following TSQL
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
IF (#dtFrom IS NOT NULL AND #dtTo IS NOT NULL)
BEGIN -- with both dates
SELECT
m.itemsId,
m.ObjectId,
0 AS [type],
STUFF((SELECT
(CAST(Sensors.SourceNameId AS nvarchar(10)) + '=' + CAST(t.Value AS nvarchar(20)) + '|')
FROM [tavl2].[tavl].[itemsData] t WITH (NOLOCK)
LEFT JOIN tavl2.tavl.Sensors WITH (NOLOCK) ON t.SensorsId = Sensors.SensorsId
WHERE t.itemsId = m.itemsId
FOR xml PATH (''), TYPE).value('.[1]', 'nvarchar(max)'), 1, 0, '') AS params
FROM
tavl.[items] m WITH (NOLOCK)
WHERE
m.ObjectId = #objId
AND m.GpsTime BETWEEN #dtFrom AND #dtTo
AND m.Valid = 1;
END
Any better solutions?

i Managed to do it using SQLCLR ,
Here is an open-source CLR That do it in a very fast time
GROUP_CONCAT string aggregate for SQL Server (hosted at codeplex)

Related

SQL Server: OPENQUERY in easy words (with example)

I am pretty new to SQL Server, and I have stumbled upon this right here:
BEGIN TRANSACTION loadTTAllocations
INSERT INTO #ttaAllocs
SELECT
company_code AS CompanyId,
job_number AS JobNo,
...
is_blocked AS IsBlocked
FROM
OPENQUERY([SRV_TimeTac],
'SELECT DISTINCT
job.individual_value_1 AS job_number,
job.individual_value_3 AS company_code,
...
now() AS queryTimeStamp
FROM
pm_altran.pm_tasks_subprojects AS taskCode
INNER JOIN
pm_altran.pm_tasks_subprojects AS job
ON job.id = taskCode.mother_id
AND job.is_done = 0
AND NOT job.is_blocked
INNER JOIN
pm_node_to_user AS n2u
ON n2u.node_id = taskCode.id
AND n2u.access = 1
AND n2u.is_todo = 1
LEFT JOIN
altran_pm_user_user_settings AS u
ON u.administrators_id = n2u.user_id
WHERE
taskCode.object_type = ''task''
AND taskCode.is_paid_non_working = 0
AND taskCode.id > 50');
SET #rowCount = ##ROWCOUNT
SET #eventDetails = 'End loadTTAllocations: ' + CAST(#rowCount as VARCHAR(10)) + ' rows affected';
COMMIT TRANSACTION loadTTAllocations
The issue is the OPENQUERY.
What I understand from the docs is basically, that it is a query just on another server. In this case the SRV_TimeTac?
So in this example, we are querying on another server called "SRV_TimeTac" and returning results to be loaded finally into the temp table called #ttaAllocs.
Is this correct?
Thank you for your help.
OPENQUERY (Transact-SQL):
Executes the specified pass-through query on the specified linked
server. This server is an OLE DB data source. OPENQUERY can be
referenced in the FROM clause of a query as if it were a table name.
OPENQUERY can also be referenced as the target table of an INSERT,
UPDATE, or DELETE statement. This is subject to the capabilities of
the OLE DB provider. Although the query may return multiple result
sets, OPENQUERY returns only the first one.
Arguments
linked_server
Is an identifier representing the name of the linked server.
' query '
Is the query string executed in the linked server. The maximum length of the string is 8 KB.
So, to answer your question, yes, that is what your query is doing. The value of linked_server in your case is SRV_TimeTac and the value of ' query ' is your long literal string. The value of ' query ' is run on the linked server and the result set returned to the server you ran OPENQUERY on. That result set is then inserted into the variable #ttaAllocs.
You interestingly then COMMIT the transaction you started before the INSERT, which seems odd considering you only inserted the value into a variable and didn't effect any persisted objects. The Table Variable may well have ended up being written to disc, rather than stored in Memory, if it got large enough but then you'd very likely be committing the transaction to tempdb.

Find Data Types and Column Names For Stored Procedure Result in SQL Server

I am using Dapper as an ORM tool to consume a SQL Server database in C# code. To do this, I am creating strongly-typed classes that mirror the database structure so that it is easy to get objects back and forth between C# and SQL Server.
To quickly model C# classes based on SQL Server table definitions (and to write unit tests that ensure that the data layer and database are in sync), I use queries like this:
SELECT
SchemaName = c.table_schema, TableName = c.table_name,
ColumnName = c.column_name, DataType = data_type,
MaxLength = ISNULL(c.CHARACTER_MAXIMUM_LENGTH, -1)
FROM
information_schema.columns c
INNER JOIN
information_schema.tables t ON c.table_name = t.table_name
AND c.table_schema = t.table_schema
AND t.table_type = 'BASE TABLE'
ORDER BY
SchemaName, TableName, ordinal_position;
This returns each schema and table name with each of its columns and data types, which makes things easy for most CRUD-style operations:
The problem I have now is creating model classes to consume certain stored procedures, which join many tables and use aliases for a lot of the columns (eg, join to the employee table twice, alias the first set of employee details as ManagerName, ManagerEmail and the second set as WorkerName, WorkerEmail, etc.) Some of these procedures return hundreds of columns, and I am having to wade through table definitions to see which columns need to be modeled as Int16/Int32/Int64, etc., plus the procedures are not set in stone at this point, and I don't want to have to manually audit these things to make sure they are in sync if I can help it.
So, my question is: does SQL Server provide a way to see "metadata" about a stored procedure's result set (ie, the column names and data types that a procedure will return)? If not, is there a setting in SSMS that will display a data type alongside the column name, or some other creative little hack that will make this task easier?
Depending on how your procedure is written you may be able to get what you need from sp_describe_first_result_set.
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-describe-first-result-set-transact-sql
You would need to parse out result set but easier then manually hunting all of the columns.

SSIS SCD wizard does a select * on my data

Visual studio hangs on me when using the Slowly Changing Dimension Wizard.
I select the correct connection.
Then I try to open the dropdown 'Table or view' to select a destination table.
At this moment visual studio hangs on me..
I have this on all client machines and on different visual studio versions and only on this specific database. In activity monitor I noticed that the wizard does a select * on all tables in the database... I have one table that has +4billion rows (+300GB). It is the select * on this table that takes so long.
Does anybody have any idea what causes the select * on my database, or why they are doing this? And even better, how to fix this?
Don't use the slowly changing dimension wizard in SSIS at all. The data flow it creates performs really badly compared to what you can write with TSQL.
A couple of assumption; you need a type 2 SCD and you are using at least SQL Server 2008 with MERGE statements available.
Instead of SSIS use the OUTPUT clause of the MERGE statement within TSQL to perform the dimension update/insert. For example:
INSERT INTO Customer_Master
SELECT
Source_Cust_ID,
First_Name,
Last_Name,
Eff_Date,
End_Date,
Current_Flag
FROM
(
MERGE
Customer_Master CM
USING
Customer_Source CS
ON
CM.Source_Cust_ID = CS.Source_Cust_ID
WHEN NOT MATCHED
THEN
INSERT VALUES
(
CS.Source_Cust_ID,
CS.First_Name,
CS.Last_Name,
CONVERT(char(10), GETDATE()-1, 101),
'12/31/2199',
'y'
)
WHEN MATCHED
AND CM.Current_Flag = 'y'
AND (CM.Last_Name <> CS.Last_Name )
THEN
UPDATE
SET
CM.Current_Flag = 'n',
CM.End_date = convert(char(10), getdate()- 2, 101)
OUTPUT
$Action Action_Out,
CS.Source_Cust_ID,
CS.First_Name,
CS.Last_Name,
convert(char(10), getdate()-1, 101) Eff_Date,
'12/31/2199' End_Date,
'y' Current_Flag
) AS MERGE_OUT
WHERE
MERGE_OUT.Action_Out = 'UPDATE';
Source: http://www.kimballgroup.com/2008/11/design-tip-107-using-the-sql-merge-statement-for-slowly-changing-dimension-processing/

Is it possible to create a generic SP to determine Median?

I am using SQL Server 2012. I guess what I am asking is should I continue on the path of researching the ability to create a SP (or UDF, but with #Temp tables probably involved, I was thinking SP) in order to have a reusable object to determine the median?
I hope this isn't too generic of a question, and is hosed, but I have spent some time researching the ability to determine a median value. Some possible hurdles include the need to pass in a string representation of the query that will return the data that I wish to perform the median on.
Anyone attempt this in the past?
Here is a stored proc I use to generate some quick stats.
Simply pass a Source, Measure and/or Filter.
CREATE PROCEDURE [dbo].[prc-Dynamic-Stats](#Table varchar(150),#Fld varchar(50), #Filter varchar(500))
-- Syntax: Exec [dbo].[prc-Dynamic-Stats] '[Chinrus-Series].[dbo].[DS_Treasury_Rates]','TR_Y10','Year(TR_Date)>2001'
As
Begin
Set NoCount On;
Declare #SQL varchar(max) =
'
;with cteBase as (
Select RowNr=Row_Number() over (Order By ['+#Fld+'])
,Measure = ['+#Fld+']
From '+#Table+'
Where '+case when #Filter='' then '1=1' else #Filter end+'
)
Select RecordCount = Count(*)
,DistinctCount = Count(Distinct A.Measure)
,SumTotal = Sum(A.Measure)
,Minimum = Min(A.Measure)
,Maximum = Max(A.Measure)
,Mean = Avg(A.Measure)
,Median = Max(B.Measure)
,Mode = Max(C.Measure)
,StdDev = STDEV(A.Measure)
From cteBase A
Join (Select Measure From cteBase where RowNr=(Select Cnt=count(*) from cteBase)/2) B on 1=1
Join (Select Top 1 Measure,Hits=count(*) From cteBase Group By Measure Order by 2 desc ) C on 1=1
'
Exec(#SQL)
End
Returns
RecordCount DistinctCount SumTotal Minimum Maximum Mean Median Mode StdDev
3615 391 12311.81 0.00 5.44 3.4057 3.57 4.38 1.06400795277565
You may want to take a look at a response that I had to this post. In short, if you're comfortable with C# or VB .NET, you could create a user defined CLR aggregate. We use CLR implementations for quite a few things, especially statistical methods that you may see in other platforms like SAS, R, etc.
This is easily accomplished by creating a User-Defined Aggregate (UDA) via SQLCLR. If you want to see how to do it, or even just download the UDA, check out the article I wrote about it on SQL Server Central: Getting The Most Out of SQL Server 2005 UDTs and UDAs (please note that the site requires free registration in order to read their content).
Or, it is also available in the Free version of the SQL# SQLCLR library (which I created, but again, it is free) available at http://SQLsharp.com/. It is called Agg_Median.
If using SQL Server 2008 or newer (which you are), you can write a function that accepts a table-valued parameter as input.
Create Type MedianData As Table ( DataPoint Int )
Create Function CalculateMedian ( #MedianData MedianData ReadOnly )
Returns Int
As
Begin
-- do something with #MedianData which is a table
End

Hidden Features of SQL Server

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
What are some hidden features of SQL Server?
For example, undocumented system stored procedures, tricks to do things which are very useful but not documented enough?
Answers
Thanks to everybody for all the great answers!
Stored Procedures
sp_msforeachtable: Runs a command with '?' replaced with each table name (v6.5 and up)
sp_msforeachdb: Runs a command with '?' replaced with each database name (v7 and up)
sp_who2: just like sp_who, but with a lot more info for troubleshooting blocks (v7 and up)
sp_helptext: If you want the code of a stored procedure, view & UDF
sp_tables: return a list of all tables and views of database in scope.
sp_stored_procedures: return a list of all stored procedures
xp_sscanf: Reads data from the string into the argument locations specified by each format argument.
xp_fixeddrives:: Find the fixed drive with largest free space
sp_help: If you want to know the table structure, indexes and constraints of a table. Also views and UDFs. Shortcut is Alt+F1
Snippets
Returning rows in random order
All database User Objects by Last Modified Date
Return Date Only
Find records which date falls somewhere inside the current week.
Find records which date occurred last week.
Returns the date for the beginning of the current week.
Returns the date for the beginning of last week.
See the text of a procedure that has been deployed to a server
Drop all connections to the database
Table Checksum
Row Checksum
Drop all the procedures in a database
Re-map the login Ids correctly after restore
Call Stored Procedures from an INSERT statement
Find Procedures By Keyword
Drop all the procedures in a database
Query the transaction log for a database programmatically.
Functions
HashBytes()
EncryptByKey
PIVOT command
Misc
Connection String extras
TableDiff.exe
Triggers for Logon Events (New in Service Pack 2)
Boosting performance with persisted-computed-columns (pcc).
DEFAULT_SCHEMA setting in sys.database_principles
Forced Parameterization
Vardecimal Storage Format
Figuring out the most popular queries in seconds
Scalable Shared Databases
Table/Stored Procedure Filter feature in SQL Management Studio
Trace flags
Number after a GO repeats the batch
Security using schemas
Encryption using built in encryption functions, views and base tables with triggers
In Management Studio, you can put a number after a GO end-of-batch marker to cause the batch to be repeated that number of times:
PRINT 'X'
GO 10
Will print 'X' 10 times. This can save you from tedious copy/pasting when doing repetitive stuff.
A lot of SQL Server developers still don't seem to know about the OUTPUT clause (SQL Server 2005 and newer) on the DELETE, INSERT and UPDATE statement.
It can be extremely useful to know which rows have been INSERTed, UPDATEd, or DELETEd, and the OUTPUT clause allows to do this very easily - it allows access to the "virtual" tables called inserted and deleted (like in triggers):
DELETE FROM (table)
OUTPUT deleted.ID, deleted.Description
WHERE (condition)
If you're inserting values into a table which has an INT IDENTITY primary key field, with the OUTPUT clause, you can get the inserted new ID right away:
INSERT INTO MyTable(Field1, Field2)
OUTPUT inserted.ID
VALUES (Value1, Value2)
And if you're updating, it can be extremely useful to know what changed - in this case, inserted represents the new values (after the UPDATE), while deleted refers to the old values before the UPDATE:
UPDATE (table)
SET field1 = value1, field2 = value2
OUTPUT inserted.ID, deleted.field1, inserted.field1
WHERE (condition)
If a lot of info will be returned, the output of OUTPUT can also be redirected to a temporary table or a table variable (OUTPUT INTO #myInfoTable).
Extremely useful - and very little known!
Marc
sp_msforeachtable: Runs a command with '?' replaced with each table name.
e.g.
exec sp_msforeachtable "dbcc dbreindex('?')"
You can issue up to 3 commands for each table
exec sp_msforeachtable
#Command1 = 'print ''reindexing table ?''',
#Command2 = 'dbcc dbreindex(''?'')',
#Command3 = 'select count (*) [?] from ?'
Also, sp_MSforeachdb
Connection String extras:
MultipleActiveResultSets=true;
This makes ADO.Net 2.0 and above read multiple, forward-only, read-only results sets on a single database connection, which can improve performance if you're doing a lot of reading. You can turn it on even if you're doing a mix of query types.
Application Name=MyProgramName
Now when you want to see a list of active connections by querying the sysprocesses table, your program's name will appear in the program_name column instead of ".Net SqlClient Data Provider"
TableDiff.exe
Table Difference tool allows you to discover and reconcile differences between a source and destination table or a view. Tablediff Utility can report differences on schema and data. The most popular feature of tablediff is the fact that it can generate a script that you can run on the destination that will reconcile differences between the tables.
Link
A less known TSQL technique for returning rows in random order:
-- Return rows in a random order
SELECT
SomeColumn
FROM
SomeTable
ORDER BY
CHECKSUM(NEWID())
In Management Studio, you can quickly get a comma-delimited list of columns for a table by :
In the Object Explorer, expand the nodes under a given table (so you will see folders for Columns, Keys, Constraints, Triggers etc.)
Point to the Columns folder and drag into a query.
This is handy when you don't want to use heinous format returned by right-clicking on the table and choosing Script Table As..., then Insert To... This trick does work with the other folders in that it will give you a comma-delimited list of names contained within the folder.
Row Constructors
You can insert multiple rows of data with a single insert statement.
INSERT INTO Colors (id, Color)
VALUES (1, 'Red'),
(2, 'Blue'),
(3, 'Green'),
(4, 'Yellow')
If you want to know the table structure, indexes and constraints:
sp_help 'TableName'
HashBytes() to return the MD2, MD4, MD5, SHA, or SHA1 hash of its input.
Figuring out the most popular queries
With sys.dm_exec_query_stats, you can figure out many combinations of query analyses by a single query.
Link
with the commnad
select * from sys.dm_exec_query_stats
order by execution_count desc
The spatial results tab can be used to create art.
enter link description here http://michaeljswart.com/wp-content/uploads/2010/02/venus.png
EXCEPT and INTERSECT
Instead of writing elaborate joins and subqueries, these two keywords are a much more elegant shorthand and readable way of expressing your query's intent when comparing two query results. New as of SQL Server 2005, they strongly complement UNION which has already existed in the TSQL language for years.
The concepts of EXCEPT, INTERSECT, and UNION are fundamental in set theory which serves as the basis and foundation of relational modeling used by all modern RDBMS. Now, Venn diagram type results can be more intuitively and quite easily generated using TSQL.
I know it's not exactly hidden, but not too many people know about the PIVOT command. I was able to change a stored procedure that used cursors and took 2 minutes to run into a speedy 6 second piece of code that was one tenth the number of lines!
useful when restoring a database for Testing purposes or whatever. Re-maps the login ID's correctly:
EXEC sp_change_users_login 'Auto_Fix', 'Mary', NULL, 'B3r12-36'
Drop all connections to the database:
Use Master
Go
Declare #dbname sysname
Set #dbname = 'name of database you want to drop connections from'
Declare #spid int
Select #spid = min(spid) from master.dbo.sysprocesses
where dbid = db_id(#dbname)
While #spid Is Not Null
Begin
Execute ('Kill ' + #spid)
Select #spid = min(spid) from master.dbo.sysprocesses
where dbid = db_id(#dbname) and spid > #spid
End
Table Checksum
Select CheckSum_Agg(Binary_CheckSum(*)) From Table With (NOLOCK)
Row Checksum
Select CheckSum_Agg(Binary_CheckSum(*)) From Table With (NOLOCK) Where Column = Value
I'm not sure if this is a hidden feature or not, but I stumbled upon this, and have found it to be useful on many occassions. You can concatonate a set of a field in a single select statement, rather than using a cursor and looping through the select statement.
Example:
DECLARE #nvcConcatonated nvarchar(max)
SET #nvcConcatonated = ''
SELECT #nvcConcatonated = #nvcConcatonated + C.CompanyName + ', '
FROM tblCompany C
WHERE C.CompanyID IN (1,2,3)
SELECT #nvcConcatonated
Results:
Acme, Microsoft, Apple,
If you want the code of a stored procedure you can:
sp_helptext 'ProcedureName'
(not sure if it is hidden feature, but I use it all the time)
A stored procedure trick is that you can call them from an INSERT statement. I found this very useful when I was working on an SQL Server database.
CREATE TABLE #toto (v1 int, v2 int, v3 char(4), status char(6))
INSERT #toto (v1, v2, v3, status) EXEC dbo.sp_fulubulu(sp_param1)
SELECT * FROM #toto
DROP TABLE #toto
In SQL Server 2005/2008 to show row numbers in a SELECT query result:
SELECT ( ROW_NUMBER() OVER (ORDER BY OrderId) ) AS RowNumber,
GrandTotal, CustomerId, PurchaseDate
FROM Orders
ORDER BY is a compulsory clause. The OVER() clause tells the SQL Engine to sort data on the specified column (in this case OrderId) and assign numbers as per the sort results.
Useful for parsing stored procedure arguments: xp_sscanf
Reads data from the string into the argument locations specified by each format argument.
The following example uses xp_sscanf
to extract two values from a source
string based on their positions in the
format of the source string.
DECLARE #filename varchar (20), #message varchar (20)
EXEC xp_sscanf 'sync -b -fproducts10.tmp -rrandom', 'sync -b -f%s -r%s',
#filename OUTPUT, #message OUTPUT
SELECT #filename, #message
Here is the result set.
-------------------- --------------------
products10.tmp random
Return Date Only
Select Cast(Floor(Cast(Getdate() As Float))As Datetime)
or
Select DateAdd(Day, 0, DateDiff(Day, 0, Getdate()))
dm_db_index_usage_stats
This allows you to know if data in a table has been updated recently even if you don't have a DateUpdated column on the table.
SELECT OBJECT_NAME(OBJECT_ID) AS DatabaseName, last_user_update,*
FROM sys.dm_db_index_usage_stats
WHERE database_id = DB_ID( 'MyDatabase')
AND OBJECT_ID=OBJECT_ID('MyTable')
Code from: http://blog.sqlauthority.com/2009/05/09/sql-server-find-last-date-time-updated-for-any-table/
Information referenced from:
SQL Server - What is the date/time of the last inserted row of a table?
Available in SQL 2005 and later
Here are some features I find useful but a lot of people don't seem to know about:
sp_tables
Returns a list of objects that can be
queried in the current environment.
This means any object that can appear
in a FROM clause, except synonym
objects.
Link
sp_stored_procedures
Returns a list of stored procedures in
the current environment.
Link
Find records which date falls somewhere inside the current week.
where dateadd( week, datediff( week, 0, TransDate ), 0 ) =
dateadd( week, datediff( week, 0, getdate() ), 0 )
Find records which date occurred last week.
where dateadd( week, datediff( week, 0, TransDate ), 0 ) =
dateadd( week, datediff( week, 0, getdate() ) - 1, 0 )
Returns the date for the beginning of the current week.
select dateadd( week, datediff( week, 0, getdate() ), 0 )
Returns the date for the beginning of last week.
select dateadd( week, datediff( week, 0, getdate() ) - 1, 0 )
Not so much a hidden feature but setting up key mappings in Management Studio under Tools\Options\Keyboard:
Alt+F1 is defaulted to sp_help "selected text" but I cannot live without the adding Ctrl+F1 for sp_helptext "selected text"
Persisted-computed-columns
Computed columns can help you shift the runtime computation cost to data modification phase. The computed column is stored with the rest of the row and is transparently utilized when the expression on the computed columns and the query matches. You can also build indexes on the PCC’s to speed up filtrations and range scans on the expression.
Link
There are times when there's no suitable column to sort by, or you just want the default sort order on a table and you want to enumerate each row. In order to do that you can put "(select 1)" in the "order by" clause and you'd get what you want. Neat, eh?
select row_number() over (order by (select 1)), * from dbo.Table as t
Simple encryption with EncryptByKey

Resources