Using Union all to SQL Queries to create Dynamic Column Names - sql

Please se my code below
set #query = 'SELECT tenantcode, locationd, name, MONTH,' +
'Year1 as' + '[' + #Year1 + ']' +
',Year2 as' + '[' + #Year2 + ']' +
',Year3 as' + '[' + #Year3 + ']' +
',Year4 as' + '[' + #Year4 + ']' +
',Year5 as' + '[' + #Year5 + ']' +
'from #SalesPerYear' +
'UNION ALL' +
'SELECT tenantcode, locationd, name, total , t1, t2,t3,t4,t5 FROM #TotalSales '
EXECUTE (#query)
That is part of my codes in the desire in achieving a final output in SQL WHERE COLUMN NAMES should be dynamic (in this case, the changing YEAR NAME such as 2011, 2012,2013 etc)
When execute my stored procedure, there is an error like this
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'tenantcode'.
When I remove the Union all, both queries worked individually. What could be the problem here.

You're missing a space between from #SalesPerYear and UNION ALL and also the following SELECT.
....
'from #SalesPerYear '
^---here
'UNION ALL' +
' SELECT tenantcode, locationd, name, total , t1, t2,t3,t4,t5 FROM #TotalSales '
^--- and here
Thats the easiest way to demonstrate it, you can of course just put a space either side of UNION ALL
' UNION ALL ' +

Related

Add users to multiple database / SQL SERVER

I have to add users to multiple database in only one script
The login was created so i only need mapped the users to his respective database and give him datareader permissions.
I think that my only problem is how select and use the database because i only can assign permission for one database (step by step)
This is my code (I know that after i gotta execute)
SELECT
'USE [' + name + N']' + CHAR(13) + CHAR(10)
+ 'create user [sd-reader] for login [sd-reader]' + CHAR(13) + CHAR(10)
+ 'EXEC sp_addrolemember ''db_datareader'', ''sd-reader'''
FROM sys.databases
WHERE database_id > 7;
The databases that i need are between 8 and 12 id
Set the result to text mode and run the query
;With Results as
(
SELECT database_id as id, cast(
'USE [' + name + N']' + CHAR(13) + CHAR(10)
+ 'create user [sd-reader] for login [sd-reader]' + CHAR(13) + CHAR(10)
+ 'EXEC sp_addrolemember ''db_datareader'', ''sd-reader''' as nvarchar(max)) as qry
FROM sys.databases
where database_id = 1
Union all
SELECT database_id as id, cast (
('USE [' + name + N']' + CHAR(13) + CHAR(10)
+ 'create user [sd-reader] for login [sd-reader]' + CHAR(13) + CHAR(10)
+ 'EXEC sp_addrolemember ''db_datareader'', ''sd-reader''' + + CHAR(13) + CHAR(10) + + CHAR(10) + Results.qry ) as nvarchar(max)) as qry
FROM sys.databases join Results on (Results.id + 1 = sys.databases.database_id)
where sys.databases.database_id > 1
)
select top 1 qry from Results
order by id desc

Turn dynamic SELECT query into UPDATE stored procedure SQL

I am rather new to this and I am having a hard time into converting the below SQL query into an UPDATE statement for a stored procedure.
SELECT 'select'+
stuff((
SELECT ',' + 'dbo.' + Function_Name + '(' + Parameters_List + ')' FROM
[SPECIFIC_DATABASE]..Specific_table c WHERE c.Table_Name = t.Table_Name FOR
XML PATH('')),1,1,'')
+' from [' + Database_Name +'].[dbo].['+Table_Name+'] '
+ 'Where Audit_ID>' + CAST(#Audit_ID as nvarchar(100))
As 'Specific Queries'
FROM (SELECT Distinct Database_Name, Table_Name FROM [SPECIFIC_DATABASE]..Specific_table) t
The UPDATE query should be something like
UPDATE Table_name
SET Column_name = Function_Name(Parameters_List)
WHERE Audit_id >= #Audit_ID
FROM [SPECIFIC_DATABASE]..Specific_table
Any suggestions and guidelines on this would be much appreciated!
I think this should give you what you want, but I don't see any any reference to a Column_Name, so I'm assuming you will hardcode that.
select 'UPDATE tbl' + stuff((
select ' set Column_Name = ' + 'dbo.' + Function_Name + '(' + Parameters_List + ')'
from [SPECIFIC_DATABASE]..Specific_table c
where c.Table_Name = t.Table_Name
for xml PATH('')
), 1, 1, '')
+ ' from [' + Database_Name + '].[dbo].[' + Table_Name + '] tbl'
+ 'Where Audit_ID>'
+ CAST(#Audit_ID as nvarchar(100)) as 'Specific Queries'
from (
select distinct Database_Name, Table_Name
from [SPECIFIC_DATABASE]..Specific_table
) t
If the answer's not right then it might be helpful if you post what is the current output of your first query and maybe some more details as to what are the contents of the table called "Specific_table".

Display count AND percentage of distinct in TSQL

I'm working in MSSQL 2008 on a stored procedure for data profiling. I have a script that returns the distinct values and count of each using the following dynamic SQL:
SELECT #SQL = N'SELECT ' + #FieldName + ', COUNT(*) AS [Frequency] FROM ' + #TableName + ' GROUP BY ' + #FieldName + ' ORDER BY [Frequency] DESC';
I would like to add percentage of each distinct count to that output. I think the technique used here would work for what I'm doing but I can't figure out how to integrate the two.
The desired output would show the distinct values, the count of each, and the percentage of each.
Thanks in advance for any help.
your query should be like
SELECT #SQL =
N'SELECT ' +
#FieldName +
', COUNT(*) AS [Frequency] '+
', (COUNT(*)* 100 / (Select Count(*) From '+#TableName+ ')) AS [percentage] ' +
'FROM ' +
#TableName +
' GROUP BY ' +
#FieldName +
' ORDER BY [Frequency] DESC';
see demo here
I wanted to share something I added to the excellent answer from #DhruvJoshi in hopes that it might help someone in the future.
I wanted to have percentages displayed with 2 decimal places and add a percentage sign to the output. Here's what I ended up using:
SELECT #SQL =
N'SELECT ' +
#FieldName +
', COUNT(*) AS [Frequency] '+
', CAST(CONVERT(DECIMAL(10,2),(COUNT(*)* 100.0 / (Select Count(*) From '+#TableName+ '))) AS nvarchar) + ''%'' AS [Percent] ' +
'FROM ' +
#TableName +
' GROUP BY ' +
#FieldName +
' ORDER BY [Frequency] DESC';
EXECUTE sp_executesql #SQL;
Hope that helps someone in the future. Thanks again #DhruvJoshi

how to do a search and replace for a string in mssql 2012

I am having to find and replace a substring over all columns in all tables in a given database.
I tried this code from sqlserver 2012 ssms but resulting in errors from http://www.dbtalks.com/uploadfile/anjudidi/find-and-replace-string-values-in-all-tables-and-column-in-s/ Find and Replace string Values in All Tables and column in SQL Serve
I think its for older version, it having problems with some of the tables names that start with a number: example dbo.123myTable
Appreciate all the help in advance
Error Print:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.153'.
UPDATE dbo.153Test2dev SET [ALCDescription] = REPLACE(convert(nvarchar(max),[ALCDescription]),'TestsMT','Glan') WHERE [ALCDescription] LIKE '%SherlinMT%'
Updated: 1
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.153'.
UPDATE dbo.153TypeTest2 SET [FormTypeDescription] = REPLACE(convert(nvarchar(max),[FormTypeDescription]),'TestsMT','Glan') WHERE [FormTypeDescription] LIKE '%SherlinMT%'
Updated: 1
Just as a guess, to add delimiters to your table names, modify the script you linked to by editing this line:
SET #sqlCommand = 'UPDATE ' + #schema + '.' + #table + ' SET [' + #columnName + '] = REPLACE(convert(nvarchar(max),[' + #columnName + ']),''' + #stringToFind + ''',''' + #stringToReplace + ''')'
and change it to
SET #sqlCommand = 'UPDATE [' + #schema + '].[' + #table + '] SET [' + #columnName + '] = REPLACE(convert(nvarchar(max),[' + #columnName + ']),''' + #stringToFind + ''',''' + #stringToReplace + ''')'
Are you sure table names may begin with a digit? If so, include them in '[' ']', like
UPDATE [dbo].[153TypeTest2].....
based in the code you linked to, try this:
SET #sqlCommand = 'UPDATE [' + #schema + '].[' + #table + '] SET [' + .....
--add square braces: ^ ^ ^ ^
You should bracket your table name in the same way as the column name in the update query (see #table now has brackets):
SET #sqlCommand = 'UPDATE ' + #schema + '.[' + #table + '] SET [' + #columnName + '] =
REPLACE(convert(nvarchar(max),[' + #columnName + '])

Single quote in a query

How can I insert an single quotes in a query ?
Example
select *, 'INSERT INTO San_Endereco (Endereco_Id, Logradouro_Id, Bairro_Id, CEP, Logradouro, Livre) VALUES
(' + CAST(Endereco_Id as varchar) + ','
+ CAST(Logradouro_Id as varchar) + ','
+ CAST(Bairro_Id as varchar) + ','
+ CAST (CEP as varchar) + ','
+ CAST(Logradouro as varchar) + ','
+ CAST(Livre as varchar) + ')' as teste
FROM San_Endereco
Before each CAST I need put the single quote. How can I do that ?
Use two single quotes: ''
select *, 'INSERT INTO San_Endereco (Endereco_Id, Logradouro_Id, Bairro_Id, CEP, Logradouro, Livre) VALUES
(''' + CAST(Endereco_Id as varchar) + ''','''
+ CAST(Logradouro_Id as varchar) + ''','''
+ CAST(Bairro_Id as varchar) + ''','''
+ CAST (CEP as varchar) + ''','''
+ CAST(Logradouro as varchar) + ''','''
+ CAST(Livre as varchar) + ''')''' as teste
FROM San_Endereco
Use double single quotes ''
If a single quote is contained in the actual data to be inserted, the command often becomes corrupted. To solve the problem, simply replace any single quote with two quotes (not the double quote character but two single-quote characters).
declare #var varchar(100)
select #var = 'txt'
select char(39)+#var+char(39) -- with single quote
select *, 'INSERT INTO San_Endereco (Endereco_Id, Logradouro_Id, Bairro_Id, CEP, Logradouro, Livre) VALUES
(''' + CAST(Endereco_Id as varchar) + ''','
+ ....
You have to use ' in string two times:
declare #var varchar(100)
select #var = 'txt'
select ' '+#var+' ' -- without single quote
select ''''+#var+'''' -- with single quote