Change headers to yellow in SQL (inside the query) - sql-server

I have a query that is just some selects with joins.
I wanted to ask if that is possible to change headers to yellow in SQL code?
SELECT a.cccn, f.dm
(SELECT
COUNT([LOC]),
SUM([OH])
FROM
smmm

it is not possible because colors are not a part of what SQL Server returns.
SQL Server returns DATA - ONLY.
SSMS is not a front end tool, it is purely an administrator's toolbox.
So, it also does not offer this function.

If i got it right you want to change the headers in the query result set for further copying, for example, to an Excel spreadsheet, then you should use aliases like this:
SELECT TOP 20
a.demand_chain As [Demand Chain], item As [DMDUnit], descr As [Descr], hist_type As [Hist type],
fcst_cnt As [Current 111 DFU Count], loc_oh_cnt As [# Active Records (CKB)], ckb_cnt As [CKB Count], oh_total As [OH Qty]
FROM
(SELECT
U_CHAINNAME AS Demand_Chain,
[ITEM],
DMDUNIT.DESCR,
COUNT(SKU.[LOC]) loc_oh_cnt,
SUM([OH]) AS OH_Total
FROM
[BYIntegration].[SCPOMGR].[SKU] SKU

Related

How to generate an excel file (.xlsx) from SQL Server

I have this query:
WITH InfoNeg AS
(
SELECT DISTINCT
n.idcliente,
CASE
WHEN DATEDIFF(MONTH, MAX(n.fechanegociacion), GETDATE()) <= 2
THEN 'Negociado 6 meses'
ELSE NULL
END AS TipoNeg
FROM
SAB2NewExports.dbo.negociaciones AS n
WHERE
Aprobacion = 'Si'
AND cerrado = 'Si'
GROUP BY
n.idcliente
), Multi AS
(
SELECT DISTINCT
idcliente, COUNT(distinct idportafolio) AS NumPorts
FROM
orangerefi.wfm.wf_master_HIST
WHERE
YEAR(Fecha_BKP) = 2021
AND MONTH(Fecha_BKP) = 08
GROUP BY
idcliente
)
SELECT DISTINCT
m.IdCliente, c.Nombre1
FROM
orangerefi.wfm.wf_master_HIST as m
LEFT JOIN
InfoNeg ON m.idcliente = InfoNeg.idcliente
LEFT JOIN
Multi ON m.IdCliente = Multi.idcliente
LEFT JOIN
SAB2NewExports.dbo.Clientes AS c ON m.IdCliente = c.IdCliente
WHERE
CanalTrabajo = 'Callcenter - Outbound' -- Cambiar aca
AND YEAR (Fecha_BKP) = 2021
AND MONTH(Fecha_BKP) = 08
AND GrupoTrabajo IN ('Alto') -- Cambiar aca
AND Bucket IN (1, 2) -- Cambiar aca
AND Multi.NumPorts > 1
AND Infoneg.TipoNeg IS NULL
When I run it, I get 30 thousand rows and the columns that I get when performing the query are: ClientID, name. I would like it to be saved in an Excel file when I run it, I don't know if it's possible.
Another question, is it possible to create a variable that stores text?
I used CONCAT(), but the text being so long is a bit cumbersome, I don't know if there is any alternative.
If you can help me, I appreciate it.
To declare a variable
DECLARE #string VARCHAR(MAX)
SET #string = concat()
then insert whatever you are concatenating
Here is an answer given by carusyte
Export SQL query data to Excel
I don't know if this is what you're looking for, but you can export the results to Excel like this:
In the results pane, click the top-left cell to highlight all the records, and then right-click the top-left cell and click "Save Results As". One of the export options is CSV.
You might give this a shot too:
INSERT INTO OPENROWSET
('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\Test.xls;','SELECT productid, price FROM dbo.product')
Lastly, you can look into using SSIS (replaced DTS) for data exports. Here is a link to a tutorial:
http://www.accelebrate.com/sql_training/ssis_2008_tutorial.htm
== Update #1 ==
To save the result as CSV file with column headers, one can follow the steps shown below:
Go to Tools->Options
Query Results->SQL Server->Results to Grid
Check “Include column headers when copying or saving results”
Click OK.
Note that the new settings won’t affect any existing Query tabs — you’ll need to open new ones and/or restart SSMS.

How to point ALL deployed SSRS reports to different shared datasource on report server?

I have more than a hundred deployed reports on a report server that basically using same shared datasource.
Now I need to repoint all of them to a different datasource.
So I am manually going through each report on a report server and pointing it to a different shared datasource.
Is any way to do that for all reports at once?
This is not a full answer but I think it points you in a direction that might get you unlocked:
I would check into the ReportServer database. I think there appear to be 2 relevant tables. [DataSource]
and
SELECT SDS.name AS SharedDsName
,SDS.[Path]
,CONVERT(xml, CONVERT(varbinary(max), content)) AS DEF
FROM dbo.[Catalog] AS SDS
WHERE SDS.Type = 5
I found a great query that hints at this here:
https://gallery.technet.microsoft.com/scriptcenter/List-connection-strings-of-1a9a9adc
That query is:
-- List connection strings of all SSRS Shared Datasources
;WITH XMLNAMESPACES -- XML namespace def must be the first in with clause.
(DEFAULT 'http://schemas.microsoft.com/sqlserver/reporting/2006/03/reportdatasource'
,'http://schemas.microsoft.com/SQLServer/reporting/reportdesigner'
AS rd)
,SDS AS
(SELECT SDS.name AS SharedDsName
,SDS.[Path]
,CONVERT(xml, CONVERT(varbinary(max), content)) AS DEF
FROM dbo.[Catalog] AS SDS
WHERE SDS.Type = 5) -- 5 = Shared Datasource
SELECT CON.[Path]
,CON.SharedDsName
,CON.ConnString
FROM
(SELECT SDS.[Path]
,SDS.SharedDsName
,DSN.value('ConnectString[1]', 'varchar(150)') AS ConnString
FROM SDS
CROSS APPLY
SDS.DEF.nodes('/DataSourceDefinition') AS R(DSN)
) AS CON
-- Optional filter:
-- WHERE CON.ConnString LIKE '%Initial Catalog%=%TFS%'
ORDER BY CON.[Path]
,CON.SharedDsName;

How to find misspellings in data

I am trying to find the misspellings in TOWN_C field. Data looks something like below. There is no specific pattern, sometimes misspelling can be at the beginning, sometimes it can be in middle or at the end. Length of misspelling can be different too.
I am using SQL Server Management Studio to execute the queries. I used SUBSTR to find out duplicates along with the left outer join. But that does not give only misspelling. I still need to go and manually look at data.
Data ->
Achampet
ACHEMPET
AGIA
AGIYA
ASHOK NAGAR
ASHOKNAGAR
ASHOKNAGER
SQL query which I am using ->
Select distinct(T3.TOWN__C)
From (Select T1.Sub_Str, Count(T1.Sub_Str) as Y
From (SELECT TOWN__C, SUBSTRING(TOWN__C, 1, 3) as Sub_Str
FROM [SALESFORCE].[dbo].[Outlet Master] group by TOWN__C)T1
Group by T1.Sub_Str having count(*)> 1)T2
Left outer join
[SALESFORCE].[dbo].[Outlet Master]T3
On T2.Sub_Str = SUBSTRING(T3.TOWN__C, 1, 3)
Order by T3.TOWN__C
Is there a way to find out all such cases using SQL or Excel or anything else?
Here's an example using SOUNDEX, to try to locate values where multiple spellings have been used for "similar" names:
declare #t table (town varchar(35) not null)
insert into #t(town) values
('Achampet'),
('ACHEMPET'),
('AGIA'),
('AGIYA'),
('ASHOK NAGAR'),
('ASHOKNAGAR'),
('ASHOKNAGER'),
('Downtown'),
('DOWNTOWN'),
('DownTown')
select
v.*
from
(select
*,
MIN(town) OVER (PARTITION BY town_sound) as minTown,
MAX(town) OVER (PARTITION BY town_sound) as maxTown
from
#t
cross apply
(select SOUNDEX(REPLACE(town,' ','')) as town_sound) u
) v
where minTown != maxTown
Note that this doesn't return "downtown" where the only variations are in capitalization, but does return all of the values in your given sample data, which I assume were all meant to be found as possible misspellings.
Also note that SOUNDEX has had a chequered history and under older versions of SQL Server it was usually recommended that a "better" soundex be implemented as a UDF. You should be able to find versions of that with a simple search, if required.
Note, also, that Soundex was specifically designed around English pronunciation. Again, you may be able to find a better tailored function as a UDF for specific other languages.
Results:
town town_sound minTown maxTown
------------- ---------- ------------- ------------
AGIA A200 AGIA AGIYA
AGIYA A200 AGIA AGIYA
ASHOK NAGAR A225 ASHOK NAGAR ASHOKNAGER
ASHOKNAGAR A225 ASHOK NAGAR ASHOKNAGER
ASHOKNAGER A225 ASHOK NAGAR ASHOKNAGER
Achampet A251 Achampet ACHEMPET
ACHEMPET A251 Achampet ACHEMPET

SQL Server Extended Events - find particular string in the syntax

How can I check with SQL Server Extended Events if some string appears in the SQL query statement?
For example: I want to find all the queries that contain the string ord_id=4 from 12:00 to 15:00 every day.
How can I trace this with extended events?
Thanks,
Ohad
In the session wizard,select sql statement starting and in global fields ,select sql text like below
and in final screen, you can filter as shown in below screenshot
You can use this Query to read Extended Events
SELECT CONVERT(XML, event_data) XMLEventData FROM sys.fn_xe_file_target_read_file(N'PathForTheFile\*.xel', NULL, NULL, NULL)
if you write * this means read all files, if you know where to look you can write your file name instead of *
After this to make it easy to the eye use the Query below, you need to modify the query for your needs.
SELECT
xexml.value('(./action[#name="username"]/value)[1]', 'varchar(400)') as UserName
,xexml.value('(./action[#name="client_hostname"]/value)[1]', 'varchar(400)') as Client_Hostname
,xexml.value('(./action[#name="collect_system_time"]/value)[1]', 'datetime') as ProcessTime
,xexml.value('(./data[#name="statement"]/value)[1]', 'nvarchar(4000)') as SQLStatement
FROM
(
SELECT CONVERT(XML, event_data) XMLEventData FROM sys.fn_xe_file_target_read_file(N'PathOfYourFiles\*.xel', NULL, NULL, NULL) f
) AS EventTable
CROSS APPLY XMLEventData.nodes('/event') n (xexml)
WHERE cast(xexml.value('(./action[#name="collect_system_time"]/value)[1]', 'datetime')as time) between '12:00:00' and '15:00:00'
AND xexml.value('(./data[#name="statement"]/value)[1]', 'nvarchar(4000)') like '%ord_id=4%'

SQL Server SUM/Group/Window Function

Good day,
I have a table as follows.
What I would love to do is add a new Column that will tabulate/summarize (anyway possible) called "New Net" by CovID/PolicyNo/CovYear/Positive(Negative) values.
In the example below the new column would look like this.
In short, what we are trying to do is SumUp all the Values in that group and only place that total in the first row of that group and zero out all the others. Any help/pointers would be appreciated with this. I have tried SQL Server Window Functions, standard SUM/GROUP.
This should meet ypur expectations:
SELECT PolicyNo ,
CovID ,
CovYear ,
p ,
net,
CASE WHEN ROW_NUMBER()OVER(PARTITION BY CovID, PolicyNo, CovYear, net ORDER BY PolicyNo) = 1 THEN net ELSE 0 END AS NewNet
FROM dbo.test1;

Resources