SET #SQL =
'SELECT
CaseStatus =
CASE Level1Status
WHEN 1100 THEN ''Case Submitted to QC''
WHEN 1200 THEN ''Pending QC''
WHEN 1400 THEN ''Passed QC''
END,
I'm currently having problems with the dynamic sql/case expression above , as I can't seem to put strings inside dynamic sql, does anyone happen to have a solution to fixing this
EDIT
AS
BEGIN
DECLARE #SQL nvarchar(4000)
SET #SQL =
'SELECT
CaseStatus =
CASE Level1Status
WHEN 1100 THEN ''Case Submitted to QC''
WHEN 1200 THEN ''Pending QC''
WHEN 1400 THEN ''Passed QC''
END,
CaseStartDateTime,
CaseEndDateTime,
StatusName,
Cell_NameDescription,
QCAnalystName,
AnalystName,
Upload_Datetime,
Requesting_Entity,
Legal_Entity_TypeDescription,
HighPriorityDescription,
DD_Level_RequiredDescription,
CountryDscr,
Maintable.KYCCaseId AS KYCCaseId
FROM
UACTc75760ab10784b51b585f082d4b25223 AS MI,
UACT175e55161660402692a53a4cdeb89bd6 AS MainTable,
UACT5996d6e5151245cab24e4e76e3e53540 AS Statuses,
UACTde5f05df6c5f4872a1e57b3cf8368301 AS AddressDetails
WHERE
(
MI.CaseStartDateTime BETWEEN ' + quotename(convert(varchar(10), #CaseStartDateTime, 120), '''') + ' AND ' + quotename(convert(varchar(10), #CaseEndDateTime, 120), '''') +
' OR
MI.CaseEndDateTime BETWEEN ' + quotename(convert(varchar(10), #CaseStartDateTime, 120), '''') + ' AND ' + quotename(convert(varchar(10), #CaseEndDateTime, 120), '''') +
' )
AND
MI.KYCCase_Id = MainTable.KYCCaseId'
IF #StatusName IS NOT NULL AND ltrim(rtrim(#StatusName)) != N''
SET #SQL = #SQL + '
AND
Statuses.SourceStatus = MainTable.Level1Status
AND
Statuses.StatusName = ' + quotename(#StatusName, '''')
IF #CountryDscr IS NOT NULL AND ltrim(rtrim(#CountryDscr)) != N''
SET #SQL = #SQL + '
AND
AddressDetails.CountryDscr = ' + quotename(#CountryDscr, '''')
IF #CellDscr IS NOT NULL AND ltrim(rtrim(#CellDscr)) != N''
SET #SQL = #SQL + '
AND
MainTable.Cell_NameDescription = ' + quotename(#CellDscr, '''')
IF #QCAnalystName IS NOT NULL AND ltrim(rtrim(#QCAnalystName)) != N''
SET #SQL = #SQL + '
AND
MainTable.QCAnalystName = ' + quotename(#QCAnalystName, '''')
IF #AnalystName IS NOT NULL AND ltrim(rtrim(#AnalystName)) != N''
SET #SQL = #SQL + '
AND
MainTable.AnalystName = ' + quotename(#AnalystName, '''')
IF #RequestingEntity IS NOT NULL AND ltrim(rtrim(#RequestingEntity)) != N''
SET #SQL = #SQL + '
AND
MainTable.Requesting_Entity = ' + quotename(#RequestingEntity, '''')
IF #EntityType IS NOT NULL AND ltrim(rtrim(#EntityType)) != N''
SET #SQL = #SQL + '
AND
MainTable.Legal_Entity_TypeDescription = ' + quotename(#EntityType, '''')
IF #HighPriority IS NOT NULL AND ltrim(rtrim(#HighPriority)) != N''
SET #SQL = #SQL + '
AND
MainTable.HighPriorityDescription = ' + quotename(#HighPriority, '''')
IF #DDLevelRequired IS NOT NULL AND ltrim(rtrim(#DDLevelRequired)) != N''
SET #SQL = #SQL + '
AND
MainTable.DD_Level_RequiredDescription = ' + quotename(#DDLevelRequired, '''')
EXEC sp_executesql #SQL
This is the entire code, The error I'm getting is
Msg 156, Level 15, State 1, Line 32
Incorrect syntax near the keyword 'Case'.
This is working fine .
Create Table #Level1Status(Id int identity ,Level1Status int)
Insert INto #Level1Status(Level1Status) values(1100),(1200),(1400)
Declare #SQL Nvarchar(Max)
SET #SQL =
'SELECT
CaseStatus =
CASE Level1Status
WHEN 1100 THEN ''Case Submitted to QC''
WHEN 1200 THEN ''Pending QC''
WHEN 1400 THEN ''Passed QC''
END from #Level1Status';
Exec SP_ExecuteSQL #SQL
Since you are concatenate your #SQL string with local variable "#xxx", in case any of thease may null, It want give any output so use ISNULL() or COALESCE() at concatenation with all local vaiable you used.
Related
I have created the below dynamic query to check if length of particular attribute is more than 50 or not. I am trying to make the length size also dynamic but getting below error.
Msg 207, Level 16, State 1, Line 7
Invalid column name '50'.
The query I came up with is as below. I am pretty new to SQL and trying to resolve this error. Thanks!
--Rule A.5.Summary :- Length
/* The 'DECLARE' statements below are used to
define standard test parameters and their datatypes. The values for these
parameters will be updated for each of the DQ dimensions/KDEs being tested */
DECLARE #DQ_DIMENSION_RULE VARCHAR(100)
DECLARE #RULE_NO VARCHAR(100)
DECLARE #TABLE_NAME VARCHAR(100)
DECLARE #DATA_ATTRIBUTE VARCHAR(100)
DECLARE #LENGTH_SIZE INT
/*The 'SET' statements below are used to
assign values to each of the test parameters declared above.
The values will depend on the DQ dimension/KDE being tested.*/
SET #DQ_DIMENSION_RULE = 'Accuracy - Negative Values'
SET #RULE_NO = 'A.4'
SET #TABLE_NAME = 'TRANSACTIONS'
SET #DATA_ATTRIBUTE = 'TRANSACTIONID'
SET #LENGTH_SIZE = 50
DECLARE #sql nvarchar(max) = N'
SELECT
' + QUOTENAME(#DQ_DIMENSION_RULE, '''') + N' AS [DQ_Dimension_Rule],
' + QUOTENAME(#RULE_NO, '''') + N' AS [Rule_No],
' + QUOTENAME(#TABLE_NAME, '''') + N' AS [Table Name],
' + QUOTENAME(#DATA_ATTRIBUTE, '''') + N' AS [Column Name],
case when SUM(CASE WHEN LEN(' + QUOTENAME(#DATA_ATTRIBUTE) + N') >' + QUOTENAME(#LENGTH_SIZE) + N' THEN 1 ELSE 0 END) > 0 then ''Y'' else ''N'' end as [Potential Issue(Y/N)]
FROM ' + QUOTENAME(#TABLE_NAME)
-- The data from 'SELECT' statement is being inserted into the summary table
--INSERT INTO summary
EXEC sp_executesql #sql;
You should not put QUOTENAME() around the integer values, the integers are not table names that you need to quote, etc.
You should just convert the integers to strings, without quotes...
DECLARE #sql nvarchar(max) = N'
SELECT
' + QUOTENAME(#DQ_DIMENSION_RULE, '''') + N' AS [DQ_Dimension_Rule],
' + QUOTENAME(#RULE_NO, '''') + N' AS [Rule_No],
' + QUOTENAME(#TABLE_NAME, '''') + N' AS [Table Name],
' + QUOTENAME(#DATA_ATTRIBUTE, '''') + N' AS [Column Name],
case when SUM(CASE WHEN LEN(' + QUOTENAME(#DATA_ATTRIBUTE) + N') >' + CAST(#LENGTHSIZE AS NVARCHAR(MAX)) + N' THEN 1 ELSE 0 END) > 0 then ''Y'' else ''N'' end as [Potential Issue(Y/N)]
FROM ' + QUOTENAME(#TABLE_NAME)
QUOTENAME(#LENGTHSIZE) => CAST(#LENGTHSIZE AS NVARCHAR(MAX))
Better than injecting it, parametrise it:
DECLARE #DQ_DIMENSION_RULE VARCHAR(100);
DECLARE #RULE_NO VARCHAR(100);
DECLARE #TABLE_NAME sysname; --Correct data type for object names
DECLARE #DATA_ATTRIBUTE VARCHAR(100);
DECLARE #LENGTH_SIZE INT;
SET #DQ_DIMENSION_RULE = 'Accuracy - Negative Values';
SET #RULE_NO = 'A.4';
SET #TABLE_NAME = 'TRANSACTIONS';
SET #DATA_ATTRIBUTE = 'TRANSACTIONID';
SET #LENGTH_SIZE = 50;
DECLARE #sql nvarchar(max) = N'
SELECT
' + QUOTENAME(#DQ_DIMENSION_RULE, '''') + N' AS [DQ_Dimension_Rule],
' + QUOTENAME(#RULE_NO, '''') + N' AS [Rule_No],
N' + QUOTENAME(#TABLE_NAME, '''') + N' AS [Table Name],
' + QUOTENAME(#DATA_ATTRIBUTE, '''') + N' AS [Column Name],
case when SUM(CASE WHEN LEN(' + QUOTENAME(#DATA_ATTRIBUTE) + N') > #LENGTH_SIZE THEN 1 ELSE 0 END) > 0 then ''Y'' else ''N'' end as [Potential Issue(Y/N)]
FROM ' + QUOTENAME(#TABLE_NAME) + N';';
EXEC sys.sp_executesql #sql, N'#LENGTH_SIZE int', #LENGTH_SIZE;
I've also changed the data type of your dynamic object and ensured that it the literal string is injected with a nvarchar notation character too.
I'd like to do a stuff command in string literal query and it give some error
The query without string literal working:
SELECT apGr.*, 'Name: ' + apGr.GroupDesc + ' | Group: ' + apGr.GroupName GroupFull ,
abc = STUFF
(
(
SELECT ',' + appGrMn.Email
FROM APP_GroupManager As appGrMn
-- You only want to combine rows for a single ID here:
WHERE appGrMn.GroupId = apGr.GroupId
FOR XML PATH (''), TYPE
).value('.', 'varchar(max)')
, 1, 1, '')
FROM App_Group apGr
WHERE apGr.GroupId = 239
The query as string literal failed:
DECLARE #WhereQuery NVARCHAR(200) = ''
DECLARE #Query NVARCHAR(500)
SET #GroupId = 5
-- Insert statements for procedure here
IF(#GroupId IS NOT NULL)
BEGIN
PRINT(#GroupId)
SET #WhereQuery = 'WHERE apGr.GroupId = ' + #GroupId
END
ELSE IF (#SystemId IS NOT NULL)
BEGIN
SET #WhereQuery = 'WHERE apGr.SystemId = ' + #SystemId
END
ELSE IF (#GroupName IS NOT NULL)
BEGIN
SET #WhereQuery = 'WHERE apGr.GroupName = ''' + #GroupName + ''''
END
SET #Query = 'SELECT ''Name: '' + apGr.GroupDesc + '' | Group: '' + apGr.GroupName GroupFull ,
abc = STUFF
(
(
SELECT '','' + appGrMn.AdministratorMail
FROM APP_GroupManager As appGrMn
-- You only want to combine rows for a single ID here:
WHERE appGrMn.GroupId = apGr.GroupId
FOR XML PATH (''), TYPE
).value(''.'', varchar(max))
, 1, 1, '') ' +
'FROM App_Group apGr ' +
'JOIN T_SensitiveLevel AS tSen ON tSen.SensitiveLevelId = apGr.SensitiveLevelId ' + #WhereQuery
PRINT #Query
EXEC(#Query)
END
The printed query looks:
5
SELECT 'Name: ' + apGr.GroupDesc + ' | Group: ' + apGr.GroupName GroupFull ,
abc = STUFF
(
(
SELECT ',' + appGrMn.AdministratorMail
FROM APP_GroupManager As appGrMn
-- You only want to combine rows for a single ID here:
WHERE appGrMn.GroupId = apGr.GroupId
FOR XML PATH ('), TYPE
).value('.', varchar(max))
, 1, 1, ') FROM App_Group apGr JOIN T_SensitiveLevel AS tSen ON tSen.SensitiveLevelId = apGr.SensitiveLevelId WHERE apGr.GroupId = 2
It not append the #WhereQuery as it should and the error is:
Msg 102, Level 15, State 1, Line 20
Incorrect syntax near '.'.
Any help on this would be appreciated.
There were some '' related syntax error. instead of '' you need to use '''' when expecting ('') in output. Where clause is truncated since #query became larger then it's length(500). I have made some changes in the query please check:
DECLARE #WhereQuery NVARCHAR(200) = ''
DECLARE #Query NVARCHAR(2000)
declare #GroupId NVARCHAR(500)
declare #SystemId NVARCHAR(500)
declare #GroupName NVARCHAR(500)
set #GroupName='a'
SET #GroupId = 5
-- Insert statements for procedure here
IF(#GroupId IS NOT NULL)
BEGIN
PRINT(#GroupId)
SET #WhereQuery = 'WHERE apGr.GroupId = ' + #GroupId
END
ELSE IF (#SystemId IS NOT NULL)
BEGIN
SET #WhereQuery = 'WHERE apGr.SystemId = ' + #SystemId
END
ELSE IF (#GroupName IS NOT NULL)
BEGIN
SET #WhereQuery = 'WHERE apGr.GroupName = ''' + #GroupName + ''''
END
SET #Query = 'SELECT ''Name: '' + apGr.GroupDesc + '' | Group: '' + apGr.GroupName GroupFull ,
abc = STUFF
(
(
SELECT '','' + appGrMn.AdministratorMail
FROM APP_GroupManager As appGrMn
-- You only want to combine rows for a single ID here:
WHERE appGrMn.GroupId = apGr.GroupId
FOR XML PATH (''''), TYPE
).value(''.'', ''varchar(max)'')
, 1, 1, '''') ' +
'FROM App_Group apGr ' +
'JOIN T_SensitiveLevel AS tSen ON tSen.SensitiveLevelId = apGr.SensitiveLevelId ' + #WhereQuery +''
PRINT #Query
EXEC(#Query)
This question already has answers here:
Find a value anywhere in a database
(18 answers)
Search all tables, all columns for a specific value SQL Server [duplicate]
(4 answers)
Closed 5 years ago.
Suppose I have string to search "Sample String" and I have 100 tables in my database.
I want to search if any of the table contains this string.
Eg. If tlbSample contains string "Sample String" then it should show it.
I tried :-
SELECT name
FROM sys.tables
WHERE name LIKE '%Sample String%'
But no luck.
Please help me.
You can use this. I have copied it from here : https://stackoverflow.com/a/13588431/400447
DECLARE #SearchStrTableName nvarchar(255), #SearchStrColumnName nvarchar(255), #SearchStrColumnValue nvarchar(255), #SearchStrInXML bit, #FullRowResult bit, #FullRowResultRows int
SET #SearchStrColumnValue = '%searchthis%' /* use LIKE syntax */
SET #FullRowResult = 1
SET #FullRowResultRows = 3
SET #SearchStrTableName = NULL /* NULL for all tables, uses LIKE syntax */
SET #SearchStrColumnName = NULL /* NULL for all columns, uses LIKE syntax */
SET #SearchStrInXML = 0 /* Searching XML data may be slow */
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (TableName nvarchar(128), ColumnName nvarchar(128), ColumnValue nvarchar(max),ColumnType nvarchar(20))
SET NOCOUNT ON
DECLARE #TableName nvarchar(256) = '',#ColumnName nvarchar(128),#ColumnType nvarchar(20), #QuotedSearchStrColumnValue nvarchar(110), #QuotedSearchStrColumnName nvarchar(110)
SET #QuotedSearchStrColumnValue = QUOTENAME(#SearchStrColumnValue,'''')
DECLARE #ColumnNameTable TABLE (COLUMN_NAME nvarchar(128),DATA_TYPE nvarchar(20))
WHILE #TableName IS NOT NULL
BEGIN
SET #TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME LIKE COALESCE(#SearchStrTableName,TABLE_NAME)
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > #TableName
AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
)
IF #TableName IS NOT NULL
BEGIN
DECLARE #sql VARCHAR(MAX)
SET #sql = 'SELECT QUOTENAME(COLUMN_NAME),DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(''' + #TableName + ''', 2)
AND TABLE_NAME = PARSENAME(''' + #TableName + ''', 1)
AND DATA_TYPE IN (' + CASE WHEN ISNUMERIC(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(#SearchStrColumnValue,'%',''),'_',''),'[',''),']',''),'-','')) = 1 THEN '''tinyint'',''int'',''smallint'',''bigint'',''numeric'',''decimal'',''smallmoney'',''money'',' ELSE '' END + '''char'',''varchar'',''nchar'',''nvarchar'',''timestamp'',''uniqueidentifier''' + CASE #SearchStrInXML WHEN 1 THEN ',''xml''' ELSE '' END + ')
AND COLUMN_NAME LIKE COALESCE(' + CASE WHEN #SearchStrColumnName IS NULL THEN 'NULL' ELSE '''' + #SearchStrColumnName + '''' END + ',COLUMN_NAME)'
INSERT INTO #ColumnNameTable
EXEC (#sql)
WHILE EXISTS (SELECT TOP 1 COLUMN_NAME FROM #ColumnNameTable)
BEGIN
PRINT #ColumnName
SELECT TOP 1 #ColumnName = COLUMN_NAME,#ColumnType = DATA_TYPE FROM #ColumnNameTable
SET #sql = 'SELECT ''' + #TableName + ''',''' + #ColumnName + ''',' + CASE #ColumnType WHEN 'xml' THEN 'LEFT(CAST(' + #ColumnName + ' AS nvarchar(MAX)), 4096),'''
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ #ColumnName + '),'''
ELSE 'LEFT(' + #ColumnName + ', 4096),''' END + #ColumnType + '''
FROM ' + #TableName + ' (NOLOCK) ' +
' WHERE ' + CASE #ColumnType WHEN 'xml' THEN 'CAST(' + #ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ #ColumnName + ')'
ELSE #ColumnName END + ' LIKE ' + #QuotedSearchStrColumnValue
INSERT INTO #Results
EXEC(#sql)
IF ##ROWCOUNT > 0 IF #FullRowResult = 1
BEGIN
SET #sql = 'SELECT TOP ' + CAST(#FullRowResultRows AS VARCHAR(3)) + ' ''' + #TableName + ''' AS [TableFound],''' + #ColumnName + ''' AS [ColumnFound],''FullRow>'' AS [FullRow>],*' +
' FROM ' + #TableName + ' (NOLOCK) ' +
' WHERE ' + CASE #ColumnType WHEN 'xml' THEN 'CAST(' + #ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ #ColumnName + ')'
ELSE #ColumnName END + ' LIKE ' + #QuotedSearchStrColumnValue
EXEC(#sql)
END
DELETE FROM #ColumnNameTable WHERE COLUMN_NAME = #ColumnName
END
END
END
SET NOCOUNT OFF
SELECT TableName, ColumnName, ColumnValue, ColumnType, COUNT(*) AS Count FROM #Results
GROUP BY TableName, ColumnName, ColumnValue, ColumnType
I am searching a query which generate html table. I found this query, but I can not understand what is use of such so many single quote used here and
why all code create in variable. I am new in sql please help me.
BEGIN
SET NOCOUNT ON;
IF #orderBy IS NULL
BEGIN
SET #orderBy = ''
END
SET #orderBy = REPLACE(#orderBy, '''', '''''');
DECLARE #realQuery NVARCHAR(MAX) = ' //this is variable which take all query as string
DECLARE #headerRow nvarchar(MAX);
DECLARE #cols nvarchar(MAX);
SELECT * INTO #dynSql FROM (' + #query + ') sub; -- how this temp table create
SELECT #cols = COALESCE(#cols + '', '''''''', '', '''') + ''['' + name + ''] AS ''''td''''''
FROM tempdb.sys.columns
WHERE object_id = object_id(''tempdb..#dynSql'')
ORDER BY column_id;
SET #cols = ''SET #html = CAST(( SELECT '' + #cols + '' FROM #dynSql ' + #orderBy + ' FOR XML PATH(''''tr''''), ELEMENTS XSINIL) AS nvarchar(max))''
EXEC sys.sp_executesql #cols, N''#html nvarchar(MAX) OUTPUT'', #html=#html OUTPUT
--in coalesce why so many '''' used
SELECT #headerRow = COALESCE(#headerRow + '''', '''') + ''<th>'' + name + ''</th>''
FROM tempdb.sys.columns
WHERE object_id = object_id(''tempdb..#dynSql'')
ORDER BY column_id;
SET #headerRow = ''<tr>'' + #headerRow + ''</tr>'';
SET #html = ''<table border="1">'' + #headerRow + #html + ''</table>'';
';
EXEC sys.sp_executesql #realQuery
,N'#html nvarchar(MAX) OUTPUT'
,#html = #html OUTPUT
END
Above query is working fine, but I can't understand it.
declare #SqlString nvarchar(max);
declare #tmpTable nvarchar(50) = '#tmpTable', #tmpColumn nvarchar(50) = 'Name'
declare #ConcatString nvarchar(max);
set #SqlString = N'Create Table ' + #tmpTable + '(' + #tmpColumn + ' nvarchar(255));
'
+ '
while(select top(1) ' + #tmpColumn + ' from ' + #tmpTable + ')
begin
if(ISNULL(#ConcatString, 0) = 0)
begin
set #ConcatString += (select top(1) ' + #tmpColumn + ' from ' + #tmpTable +') ' + '
end
else
begin
set #ConcatString += '','' + (select top(1) ' + #tmpColumn + ' from ' + #tmpTable +')
end
end'
--print #SqlString
EXEC sp_executesql #SqlString, N'#ConcatString nvarchar(max)', #ConcatString = 0
select #ConcatString as ConcatString
Msg 4145, Level 15, State 1, Line 4
An expression of non-boolean type specified in a context where a condition is expected, near 'begin'.