Trigger a dynamic SQL Server stored procedure to run every day - sql-server

I have a dynamic stored procedure which runs in SSMS. Is it possible to convert this proc into a function so when ever I do
exec function stored.proc
I can run this from my ETL?
My query as below -
create procedure dbo.bear_load
as
set nocount on;
Declare #cols as NVARCHAR(MAX), #query as NVARCHAR(MAX), #Result as NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(FIELD_NAME)
from bear_crossjoin
group by Field_Name, FIELDNUMBER
order by FIELDNUMBER
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = N'SELECT ' + #cols + N'
from
(
select substring, Field_Name,
rn = row_number() over(partition by field_name order by fieldnumber)
from bear_crossjoin
) x
pivot
(
max(substring)
for Field_Name in (' + #cols + N')
) p '
set #Result= ' select ' + #query
EXEC (#query)
GO
exec dbo.bear_load
Any help very much appreciated.
Arun

Related

How do I create a new table from the results of a dynamic SQL statement in T-SQL

I'm trying to use the results from this dynamic SQL statement, to create a new table
DECLARE #cols NVARCHAR(MAX), #query NVARCHAR(MAX);
SET #cols = STUFF((SELECT DISTINCT
',' + QUOTENAME(c.[ClassCode])
FROM [Sandbox].[dbo].Test2 c
FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '');
SET #query = 'SELECT [Name_ID], ' + #cols +
'FROM (SELECT [Name_ID],
[ClassCodeYN] AS [amount],
[ClassCode] AS [category]
FROM [Sandbox].[dbo].[Test2]) x
PIVOT (COUNT(amount) FOR category IN (' + #cols + ')) p';
EXECUTE #query
I've tried to use INSERT INTO and CREATE TABLE and get either
Incorrect syntax near the keyword 'EXECUTE'
or
Must DECLARE #query
errors.
You should be able to just add into <table> to your existing query:
DECLARE #cols NVARCHAR(MAX), #query NVARCHAR(MAX);
SET #cols = STUFF((SELECT DISTINCT
',' + QUOTENAME(c.[ClassCode])
FROM [Sandbox].[dbo].Test2 c
FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '');
SET #query = 'SELECT [Name_ID], ' + #cols +
' INTO MyTable' +
' FROM (SELECT [Name_ID],
[ClassCodeYN] AS [amount],
[ClassCode] AS [category]
FROM [Sandbox].[dbo].[Test2]) x
PIVOT (COUNT(amount) FOR category IN (' + #cols + ')) p';
Exec sp_executesql #query

Create indexed view from defined pivot table

I have a requirement of creating a view for pivot table
This is my source table
According to my requirement I have created the following pivot table
DECLARE #cols AS NVARCHAR(MAX), #query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(Date)
from Salse_Data
group by Date
order by Date
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT Product,' + #cols + ' from
(
select Product, Date, Salse
from Salse_Data
) x
pivot
(
sum(Salse)
for Date in (' + #cols + ')
) p '
execute(#query);
Output is
I need to create an indexed view(Materialized View) above query
So i used procedure to create the view
CREATE PROCEDURE [dbo].[ProductSalse_By_Year_Proc_4]
AS
BEGIN
DECLARE #cols AS NVARCHAR(MAX), #query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(Date)
from Salse_Data
group by Date
order by Date
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'CREATE VIEW abcd with schemabinding as SELECT Product,' + #cols + ' from
(
select Product, Date, Salse
from Salse_Data
) x
pivot
(
sum(Salse)
for Date in (' + #cols + ')
) p '
EXECUTE(#query)
END
GO
this execuce without errors but not created the view.
Could you please help on this issue?

ms sql pivot does not work

I'm trying to transpose a simple table from rows to columns with two string variables. I went trough several examples from the web without success. The number of rows will vary so I need to transpose the table dynamically. The following code at least does not produce an error but does not generate the result!
The sample table
create table #Encabezado
(
NodeName nvarchar(100),
NodeValue nvarchar(100)
)
INSERT INTO #Encabezado (NodeName, NodeValue) VALUES
('RUTEmisor','88888888-8'),
('RznSoc','EMPRESA DE PRUEBA'),
('GiroEmis','Informatica'),
('Acteco','1'),
('CdgSIISucur','59529595'),
('DirOrigen','Teatinos 120'),
('CmnaOrigen','Santiago'),
('CiudadOrigen','Santiago')
GO
The unpivot code
DECLARE #colsUnpivot AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #colsUnpivot
= stuff((select ','+quotename(C.column_name)
from information_schema.columns as C
where C.table_name = '#Encabezado' and
C.column_name like '%Name'
for xml path('')), 1, 1, '')
set #query
= 'select NodeName,
Nodevalue
from #Encabezado
unpivot
(
NodeName
for NodeName in ('+ #colsunpivot +')
) u'
exec sp_executesql #query;
Any help would be appreciated
Sequelspear once said : "To Pivot or UnPivot, That's the question."
declare #cols NVARCHAR(MAX) = stuff((select ','+quotename(Nodename) from #Encabezado group by Nodename for xml path('')),1,1,'');
declare #query NVARCHAR(MAX) = 'select * from #Encabezado pivot (max(NodeValue) for NodeName IN ('+ #cols +')) pvt';
exec sp_executesql #query;
To Dynamically Pivot
Declare#Cols AS NVARCHAR(MAX),#SQL AS NVARCHAR(MAX);
Set #Cols = Stuff((Select Distinct ',' + QuoteName(NodeName)
From #Encabezado
For XML Path(''), Type
).value('.', 'varchar(max)'),1,1,'')
Set #SQL = 'Select * From #Encabezado
Pivot (
max(NodeValue)
For [NodeName] in (' + #Cols + ')
) p '
Exec (#SQL)
Returns
Now, to unpivot, consider the following:
Declare #User table (ID int,Active bit,First_Name varchar(50),Last_Name varchar(50),EMail varchar(50))
Insert into #User values
(1,1,'John','Smith','john.smith#email.com'),
(2,0,'Jane','Doe' ,'jane.doe#email.com')
Declare #XML xml = (Select * from #User for XML RAW)
Select ID = r.value('#ID','int')
,Active = r.value('#Active','bit')
,Item = attr.value('local-name(.)','varchar(100)')
,Value = attr.value('.','varchar(max)')
From #XML.nodes('/row') as A(r)
Cross Apply A.r.nodes('./#*') AS B(attr)
Where attr.value('local-name(.)','varchar(100)') not in ('ID','Active')
Returns

Convert Query into View

I have the following query and I need to store it as a view, I am lost and any help appreciated. I am using Microsoft SQL Server 2016. I have been wrestling with returning the data in a form I need using online guides but now I have it but I am unable to convert to a view.
DECLARE #T AS TABLE(y INT NOT NULL PRIMARY KEY);
DECLARE
#cols AS NVARCHAR(MAX),
#y AS INT,
#sql AS NVARCHAR(MAX);
-- Construct the column list for the IN clause
SET #cols = STUFF(
(SELECT N',' + QUOTENAME(y) AS [text()]
FROM (SELECT DISTINCT AttName AS y FROM vwObjectAttributesValuesAsRows) AS Y
ORDER BY y
FOR XML PATH('')),
1, 1, N'');
-- Construct the full T-SQL statement
-- and execute dynamically
SET #sql = N'SELECT *
FROM (SELECT ObjectID, ObjectName, AttName, value
FROM vwObjectAttributesValuesAsRows
) AS D
PIVOT(Max(value) FOR AttName IN(' + #cols + N')) AS P;';
EXEC sp_executesql #sql;
GO

Sql Server Query Date Issue

This executes correctly: (It is weird that I needed to use '' by the date for it to actually execute)
DECLARE
#cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.statcolumnname) FROM [85137_PHY_Long_PG] c FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
set #query = 'SELECT statdate, ' + #cols + ' from
(
select statdate, statcolumnname, statcolumnvalue
from [85137_PHY_Long_PG]
) x
pivot
(
min(statcolumnvalue)
for statcolumnname in (' + #cols + ')
) p WHERE statdate BETWEEN ''2012-04-01 12:15:00'' AND ''2012-04-01 12:45:00'' ORDER BY statdate'
execute(#query)
Now I want to replace the dates with variables:
DECLARE
#cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX),
#from AS NVARCHAR(MAX),
#to AS NVARCHAR(MAX);
set #from = '2012-04-01 12:15:00'
set #to = '2012-04-01 12:45:00'
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.statcolumnname) FROM [85137_PHY_Long_PG] c FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
set #query = 'SELECT statdate, ' + #cols + ' from
(
select statdate, statcolumnname, statcolumnvalue
from [85137_PHY_Long_PG]
) x
pivot
(
min(statcolumnvalue)
for statcolumnname in (' + #cols + ')
) p WHERE statdate BETWEEN ''+#from+'' AND ''+#to+'' ORDER BY statdate'
execute(#query)
I get the following error:Conversion failed when converting character string to smalldatetime data type
Changing the where statement to the following:
WHERE statdate BETWEEN ''+convert(smalldatetime,#from)+'' AND ''+convert(smalldatetime,#to)+'' ORDER BY statdate'
Still gives me the same error, just can't seem to replace the dates as variables
'' is not weird; it is a notation that enables apostrophes inside varchars.
When concatenating make sure that you are not trying to concatenate anything other than (n)varchars and (n)chars because Sql Server will attempt to convert them to other datatypes; in your case, in smalldatetime. You might avoid this trouble by explicitly converting your parameter dates to nvarchars before/during concatenation, but better solution is to use sp_executesql and parameters.
If you leave parameters inside query:
set #query = 'SELECT statdate, ' + #cols + ' from
(
select statdate, statcolumnname, statcolumnvalue
from [85137_PHY_Long_PG]
) x
pivot
(
min(statcolumnvalue)
for statcolumnname in (' + #cols + ')
) p WHERE statdate BETWEEN #from AND #to ORDER BY statdate'
You can execute it with parameters:
exec sp_executesql #query, N'#from datetime, #to datetime', #from=#from_variable, #to=#to_variable
Where #from_variable and #to_variable are datetime variables defined earlier in batch.
UPDATE:
If your ultimate goal is to wrap this code in stored procedure, here is a template:
create proc MyProc (#dateFrom smalldatetime, #dateTo smalldatetime)
as
DECLARE
#cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.statcolumnname)
FROM [85137_PHY_Long_PG] c
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
set #query = 'SELECT statdate, ' + #cols + ' from
(
select statdate, statcolumnname, statcolumnvalue
from [85137_PHY_Long_PG]
) x
pivot
(
min(statcolumnvalue)
for statcolumnname in (' + #cols + ')
) p WHERE statdate BETWEEN #from AND #to ORDER BY statdate'
exec sp_executesql #query, N'#from smalldatetime, #to smalldatetime', #from=#dateFrom, #to=#dateTo
Herewith the solution:
DECLARE
#cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX),
#internal_fromdate AS SMALLDATETIME,
#internal_todate AS SMALLDATETIME;
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.statcolumnname) FROM [85137_PHY_Long_PG] c FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
set #internal_fromdate = '2012-04-01 12:15:00';
set #internal_todate = '2012-04-01 12:45:00';
set #query = 'SELECT statdate, ' + #cols + ' from
(
select statdate, statcolumnname, statcolumnvalue
from [85137_PHY_Long_PG]
) x
pivot
(
min(statcolumnvalue)
for statcolumnname in (' + #cols + ')
) p WHERE statdate BETWEEN #FromDate AND #ToDate ORDER BY statdate'
exec sp_executesql #query, N'#FromDate SMALLDATETIME, #ToDate SMALLDATETIME', #FromDate=#internal_fromdate, #ToDate=#internal_todate
UPDATE
Ok, I have tried the following variations:
create proc MyProc9 (#tableName varchar,#dateFrom smalldatetime, #dateTo smalldatetime)
AS
DECLARE
#cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.statcolumnname)
FROM [85137_PHY_Long_MP] c
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
set #query = 'SELECT statdate, ' + #cols + ' from
(
SELECT statdate, statcolumnname, statcolumnvalue
from #table
) x
pivot
(
min(statcolumnvalue)
for statcolumnname in (' + #cols + ')
) p WHERE statdate BETWEEN #from AND #to ORDER BY statdate'
exec sp_executesql #query, N'#table varchar,#from smalldatetime, #to smalldatetime', #table=#tableName,#from=#dateFrom, #to=#dateTo
Error: Must declare the table variable "#table".
Tried '+#tableName+' in the #query string: Incorrect syntax near '8'.
Tried '+QUOTENAME(#tableName)+' in the #query string: Invalid object name '8'.
Tried ['+#tableName+'] in the #query string: Invalid object name '8'.
Tried QUOTENAME(#table) in the #query string: Invalid object name '8'.
Tried [85137_PHY_Long_MP] in the #query string: Works correctly, just want to replace this.
Tried [#tableName] in the #query string: Invalid object name '#tableName'.
Tried #tableName in the #query string: Must declare the table variable "#tableName".
I don't understand how to resolve the problem

Resources