Want to set Collation in Select statement in SQL.
I have below SQL query for which I get error :
Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AI" in the equal to operation.
I have idea for setting collation for joins, in this case I dont have idea.
Below is the SQL Query for which I am trying to set COLLATE SQL_Latin1_General_CP1_CI_AI,
SET #ColumnNames_CSV_Responses_Smoker_Retail = ' ';
SELECT #ColumnNames_CSV_Responses_Smoker_Retail = COALESCE(#ColumnNames_CSV_Responses_Smoker_Retail, '') +
CASE WHEN QuestionType IN (2, 3, 4)
AND EXISTS (SELECT *
FROM Optiontable
WHERE Option_Code = '1001'
AND Optiontable.Question_ID = Question.QuestionID) THEN 'dbo.ReplaceBrandIDWithCode(''' + CAST(QuestionID AS varchar) + ''',[' + CAST(QuestionID AS varchar) + ']) AS [' + CAST(QuestionID AS varchar) + '],'
WHEN QuestionType IN (3) THEN 'REPLACE(RTRIM(LTRIM([' + CAST(QuestionID AS varchar) + '])),'' '', ''#'') AS [' + CAST(QuestionID AS varchar) + '],'
WHEN QuestionType IN (4) THEN 'REPLACE(REPLACE(SUBSTRING(RTRIM(LTRIM([' + CAST(QuestionID AS varchar) + '])),1, LEN(RTRIM(LTRIM([' + CAST(QuestionID AS varchar) + ']))) - 1),''^'', ''#''),'','','''') AS [' + CAST(QuestionID AS varchar) + '],'
ELSE 'REPLACE(RTRIM(LTRIM([' + CAST(QuestionID AS varchar) + '])),'','', '' '') AS [' + CAST(QuestionID AS varchar) + '],'
END
FROM Question
WHERE CAST(QuestionID AS varchar)IN (SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #Table_Name)
ORDER BY QuestionSeqNumber;
Any Help will be Appreciated, Thanks.
Related
I am trying to get the total sum from columns of a specific data type(money) for multiple tables in a database. Currently I am able to get the list of columns from specific tables but I am unable to get the sums from those columns.
This is what I have now
use database 1
Select + Column_Name
From information_schema.columns
Where TABLE_NAME = 'claimant'
and data_type = 'money'
The result looks something like below
table_name
column_name
table_1
column_a
table_1
column_b
table_1
column_c
what I would like
table_name
column_name
total_sum
table_1
column_a
66.20
table_1
column_b
300.50
table_1
column_c
5389.42
update for #Squirrel Here is the code I have but it's still giving me issues with truncation.
{
declare #sql nvarchar(max);
select #sql = 'with cte as (' + char(13)
+ 'select' + char(13)
+ string_agg(char(9) + quotename(column_name) + ' = sum(' + quotename(COLUMN_NAME) + ')', ',' + char(13)) + char(13)
+ 'from ' + max(quotename(table_name)) + char(13)
+ ')' + char(13)
+ 'select a.table_name, a.column_name, a.total_sum ' + char(13)
+ 'from cte ' + char(13)
+ 'cross apply (' + char(13)
+ char(9) + 'values' + char(13)
+ string_agg(char(9) + '(''' + table_name + ''',''' + column_name + ''',' + quotename(COLUMN_NAME) + ')', ',' + char(13)) + char(13)
+ ') a (table_name, column_name, total_sum)'
from information_schema.columns AS A
INNER JOIN EDL01.STAGING.TABLE_DETAILS B
ON A.TABLE_NAME = B.DEST_TABLE_NAME
where A.table_name = B.DEST_TABLE_NAME
and data_type = 'money'
print #sql
exec sp_executesql #sql
}
below is the create table
CREATE TABLE [staging].[TABLE_DETAILS](
[SOURCE_TABLE_NAME] [varchar](100) NULL,
[DEST_TABLE_NAME] [varchar](100) NULL,
[TYPE] [varchar](10) NULL,
[PRIORITY] [int] NULL,
[SOURCE_TABLE_DATABASE] [varchar](50) NULL,
[SOURCE_TABLE_SCHEMA] [varchar](50) NULL,
[DEST_TABLE_DATABASE] [varchar](50) NULL,
[DEST_TABLE_SCHEMA] [varchar](50) NULL
) ON [PRIMARY]
GO
Below is part of the results
select a.table_name, a.column_name, a.total_sum
from cte
cross apply (
values
('PAYMENT','BILLEDAMOUNT',[BILLEDAMOUNT]),
('PAYMENT','AMOUNT',[AMOUNT]),
('SIMS_PAYMENT','CHECKAMOUNT',[CHECKAMOUNT]),
('BILLREVIEWHEADER','JURISDICTIONAMOUNT1',[JURISDICTIONAMOUNT1]),
('BILLREVIEWHEADER','JURISDICTIONAMOUNT2',[JURISDICTIONAMOUNT2]),
('BILLREVIE
You need to form the query dynamically and then execute it using sp_executesql or exec()
Note : char(9) is tab, char(13) is carriage return. These are added to format the query so that it is readable when you print it out for verification.
declare #sql nvarchar(max);
select #sql = 'with cte as (' + char(13)
+ 'select' + char(13)
+ string_agg(char(9) + quotename(column_name) + ' = sum(' + quotename(column_name) + ')', ',' + char(13)) + char(13)
+ 'from ' + max(quotename(table_name)) + char(13)
+ ')' + char(13)
+ 'select a.table_name, a.column_name, a.total_sum ' + char(13)
+ 'from cte ' + char(13)
+ 'cross apply (' + char(13)
+ char(9) + 'values' + char(13)
+ string_agg(char(9) + '(''' + table_name + ''', ''' + column_name + ''',' + quotename(column_name) + ')', ',' + char(13)) + char(13)
+ ') a (table_name, column_name, total_sum)'
from information_schema.columns
where table_name = 'table_1'
and data_type = 'money'
print #sql
exec sp_executesql #sql
For your sample table, the generated dynamic query is
with cte as (
select
[column_a] = sum([column_a]),
[column_b] = sum([column_b]),
[column_c] = sum([column_c])
from [table_1]
)
select a.table_name, a.column_name, a.total_sum
from cte
cross apply (
values
('table_1', 'column_a',[column_a]),
('table_1', 'column_b',[column_b]),
('table_1', 'column_c',[column_c])
) a (table_name, column_name, total_sum)
EDIT
using a loop to iterate each table. Basically it execute above query for each of the table and insert the result into a temp table
see db<>fiddle demo
for earlier SQL Server version without string_agg(), use for xml path
select #sql = 'with cte as (' + char(13)
+ 'select' + char(13)
+ stuff
(
(
select ',' + quotename(COLUMN_NAME) + ' = sum(' + quotename(COLUMN_NAME) + ')'
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = #table
and DATA_TYPE = 'money'
for xml path('')
),
1, 1, ''
) + char(13)
+ 'from ' + max(quotename(#table)) + char(13)
+ ')' + char(13)
+ 'select a.table_name, a.column_name, a.total_sum ' + char(13)
+ 'from cte ' + char(13)
+ 'cross apply (' + char(13)
+ char(9) + 'values' + char(13)
+ stuff
(
(
select ',' + '(''' + TABLE_NAME + ''', ''' + COLUMN_NAME + ''',' + quotename(COLUMN_NAME) + ')'
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = #table
and DATA_TYPE = 'money'
for xml path('')
),
1, 1, ''
)
+ ') a (table_name, column_name, total_sum)' + char(13)
I have a query of the form
SELECT '(''' +
SomeVarCharColumn +
''',' +
CONVERT(NVARCHAR(MAX), SomeIntColumn) +
',' +
CONVERT(NVARCHAR(MAX), SomeOtherIntColumn)
+ ')'
FROM SomeTable
and all the results are NULL. Any idea where I'm going wrong?
null + 1 is null
null + 'things' is null
try this instead:
select '('''
+ isnull(somevarcharcolumn,'')
+ ''','
+ isnull(convert(nvarchar(max), someintcolumn),'null')
+ ','
+ isnull(convert(nvarchar(max), someotherintcolumn),'null')
+ ')'
from sometable
If any column is NULL, then the value is NULL. Use COALESCE():
SELECT '(''' + COALESCE(SomeVarCharColumn, '') + ''',' +
COALESCE(CONVERT(NVARCHAR(MAX), SomeIntColumn), '') + ',' +
COALESCE(CONVERT(NVARCHAR(MAX), SomeOtherIntColumn), '') + ')'
FROM SomeTable
Use the CONCAT() function. When null values are encountered they are simply omitted from the resulting string. Additionally, int to char conversions are implicit no need for the convert, you can find a chart of implicit conversions here https://msdn.microsoft.com/en-us/library/ms187928.aspx
SELECT
CONCAT('(''',SomeVarCharColumn,''',',SomeIntColumn,',',SomeOtherIntColumn,')') AS NewVarchar
FROM SomeTable
I want to pass the results of the following query into its own query:
SELECT
'CREATE INDEX [missing_index_'
+ CONVERT (VARCHAR, mig.index_group_handle) + '_'
+ CONVERT (VARCHAR, mid.index_handle) + '_'
+ LEFT (PARSENAME (mid.statement, 1),32) + ']'
+ ' ON ' + mid.statement + ' (' + ISNULL(mid.equality_columns, '')
+
CASE
WHEN mid.equality_columns IS NOT NULL AND mid.inequality_columns IS NOT NULL
THEN ','
ELSE ''
END
+ ISNULL(mid.inequality_columns, '') + ')'
+ ISNULL(' INCLUDE (' + mid.included_columns + ')', '') AS create_index_statement
FROM sys.dm_db_missing_index_groups mig
INNER JOIN sys.dm_db_missing_index_group_stats migs ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details mid ON mig.index_handle = mid.index_handle
WHERE
migs.avg_total_user_cost * (migs.avg_user_impact / 100.0)
* (migs.user_seeks + migs.user_scans) > 10
You could concatenate all your rows into a single string, the execute that using sp_executesql
-- BUILD STATEMENT
DECLARE
#SQL NVARCHAR (MAX) = (
SELECT
'CREATE INDEX [missing_index_' + CONVERT (
VARCHAR(MAX)(,
mig.index_group_handle
) + '_' + CONVERT (VARCHAR, mid.index_handle) + '_' + LEFT (
PARSENAME (mid.statement, 1),
32
) + ']' + ' ON ' + mid.statement + ' (' + ISNULL(mid.equality_columns, '') + CASE
WHEN mid.equality_columns IS NOT NULL
AND mid.inequality_columns IS NOT NULL THEN
','
ELSE
''
END + ISNULL(mid.inequality_columns, '') + ')' + ISNULL(
' INCLUDE (' + mid.included_columns + ')',
''
) + ';' AS create_index_statement
FROM
sys.dm_db_missing_index_groups mig
INNER JOIN sys.dm_db_missing_index_group_stats migs ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details mid ON mig.index_handle = mid.index_handle
WHERE
migs.avg_total_user_cost * (migs.avg_user_impact / 100.0) * (
migs.user_seeks + migs.user_scans
) > 10 FOR XML PATH (''),
TYPE ).
VALUE
('.', 'NVARCHAR(MAX)');
-- EXECUTE STATEMENT
EXECUTE sp_executesql #SQL;
HOWEVER I would strongly advise against creating indexes is this manner, it does there are too many other factors to consider when creating indexes, this does not consider a read/write ratio, or lots of similar suggestions that could be amalgamated into one etc. Indexing is as much of an art than it is a science, so I don't think there is a magic fix query that can do this for you.
Usually when we use select statement it displays the output, but when insert into is used,stores the result into temp table.i want to do both.Display result and store in temp table as well in dynamic sql.
IF #DisplayInSelect IS NOT NULL
SET #DisplayInSelect = ','+#DisplayInSelect
SET #SQL = 'IF EXISTS (SELECT DISTINCT a.'+#column_name+' FROM ['+#TableName+'] a where '+#FullCondition+' )'+
'SELECT DISTINCT ''Error at column: '+#Column_name+''' as [Error Records if found any are shown below],'''+ISNULL(#CustomErrorMessage,'ERROR')+''''+ISNULL(#DisplayInSELECT,'')+', a.'+#column_name+',* FROM ['+#TableName+'] a where '+#FullCondition+'
INSERT INTO ##error_check(SELECT DISTINCT ''Error at column: '+#Column_name+''' as [Error Records if found any are shown below],'''+ISNULL(#CustomErrorMessage,'ERROR')+''''+ISNULL(#DisplayInSELECT,'')+', a.'+#column_name+', *FROM ['+#TableName+'] a where '+#FullCondition+');
PRINT('IQR1 sql is'+#SQL)
EXEC(#SQL)
END
You have to use insert into table along with Exec. Try like this,
IF #DisplayInSelect IS NOT NULL
SET #DisplayInSelect = ',' + #DisplayInSelect
SET #SQL = 'IF EXISTS (SELECT DISTINCT a.' + #column_name + ' FROM [' + #TableName + '] a where ' + #FullCondition + ' )' + 'SELECT DISTINCT ''Error at column: ' + #Column_name + ''' as [Error Records if found any are shown below],''' + ISNULL(#CustomErrorMessage, 'ERROR') + '''' + ISNULL(#DisplayInSELECT, '') + ', a.' + #column_name + ',* FROM [' + #TableName + '] a where ' + #FullCondition + '
SELECT DISTINCT ''Error at column: ' + #Column_name + ''' as [Error Records if found any are shown below],''' + ISNULL(#CustomErrorMessage, 'ERROR') + '''' + ISNULL(#DisplayInSELECT, '') + ', a.' + #column_name + ', *FROM [' + #TableName + '] a where ' + #FullCondition + ';'
--To Save
INSERT INTO ##error_check
EXEC (#SQL)
PRINT (' IQR1 sql IS ' + #SQL)
--To Display
EXEC (#SQL)
This question already has answers here:
Incorrect syntax near ']'.?
(3 answers)
Closed 8 years ago.
After trying to find out the problem myself doing some debugging
I have found that #cols and #cols2 variables are not bringing a result , I have PRINT
PRINT('INSERT INTO [' + #Destination_Database_Name + '].[dbo].[' + #tablename + '] (' + #cols2 + ']' + ') SELECT [' + #cols2 + ']' + ' FROM [' + #Source_Database_Name + '].[dbo].[' + #tablename + ']');
And the statement will not show the output all I get is
(1 row(s) affected)
(1 row(s) affected)
I am here2
c365online_script1
I am here3
tCompany
This is the section of the code which I think is the problem
Print 'I am here2'
SET IDENTITY_INSERT c365online_script1.dbo.tCompany ON
declare #cols2 varchar(max)
PRINT #cols2
select #cols2 = (Select Stuff((Select '],[' + C.COLUMN_NAME From INFORMATION_SCHEMA.COLUMNS As C Where C.TABLE_SCHEMA = T.TABLE_SCHEMA And C.TABLE_NAME = T.TABLE_NAME Order By C.ORDINAL_POSITION For Xml Path('')), 1, 2, '') As Columns From INFORMATION_SCHEMA.TABLES As T WHERE T.TABLE_NAME = #tablename)
PRINT('INSERT INTO [' + #Destination_Database_Name + '].[dbo].[' + #tablename + '] (' + #cols2 + ']' + ') SELECT [' + #cols2 + ']' + ' FROM [' + #Source_Database_Name + '].[dbo].[' + #tablename + ']');
PRINT #Destination_Database_Name
Print 'I am here3'
Print #tablename
END
I can post full code on request
Try
SET #cols2 = (Select....)
instead of
SELECT #cols2 = (Select....)
This is a NULL concatenation problem. Try initializing your variables as empty strings, like this, and see what you learn about the results of your query:
declare #tablename varchar(128) = '',
#Destination_Database_Name varchar(128) = '',
#Source_Database_Name varchar(128) = '';