String literal in SQL query field - sql

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)

Related

Conversion failing when applying PIVOTED SCRIPT

i am having a data conversion issues when applying this un-pivoted script on my dynamic columns SSRS report .every time SSRS Report is executed the header columns are supposedly to change .
IF OBJECT_ID('tempdb..##Temp') IS NOT NULL
DROP TABLE ##Temp;
DECLARE #ObjectName VARCHAR(100) = '[AdventureWorks2016].[Sales].[SalesOrderHeader]' ,
#KeyColumn VARCHAR(100) = '[SalesOrderID]';
DECLARE #ColumnNames NVARCHAR(MAX)= '' ,
#Values NVARCHAR(MAX)= '' ,
#SQL NVARCHAR(MAX)= '';
SELECT #ColumnNames += ',
' + QUOTENAME([ShipDate]) ,
#Values += ',
' + QUOTENAME([ShipDate]) + ' = CONVERT(VARCHAR(100), '
+ QUOTENAME([ShipDate]) + ')'
FROM [AdventureWorks2016].[Sales].[SalesOrderHeader]
WHERE '[Sales].[SalesOrderHeader]' = #ObjectName
AND [ShipDate] <> #KeyColumn;
SET #SQL = N'Select * into ##Temp
FROM
(
SELECT ' + #KeyColumn + #Values + '
FROM ' + #ObjectName + '
) AS DRV
UNPIVOT
(
Value FOR ColumnName IN (' + STUFF(#ColumnNames, 1, 1, '') + ')
) AS UnPVT;';
EXEC sp_executesql #SQL;
SELECT *
FROM ##Temp

Can this dynamic SQL be replaced with the regular SQL to improve performance?

I am using the following dynamic query, but see that the performance is slow. I am not a big fan of dynamic SQL, and am looking for, if possible, a good clean and fast SQL alternative for the following. Thanks a million ton in advance! Here are some details:
In the following code, the final table missingfields_xxxx lists out the rows where we have a missing rule field.
table_name has the column rule that holds the column name of the table trans_modelname (this table can be found in the dynamic part of the sql)
DECLARE #rule NVARCHAR(MAX)
DECLARE #PeriodNumber INT = 1
DECLARE #SelectList NVARCHAR(MAX)
DECLARE #WhereList NVARCHAR(MAX)
DECLARE #SQL NVARCHAR(MAX)
DECLARE #ModelName as NVARCHAR(MAX) = 'modelname'
--DECLARE #MaxPeriods INT = 8
DECLARE #MaxPeriods INT
SELECT #MaxPeriods = count (*)
FROM
(
SELECT [rule]
FROM table_name
WHERE ModelName = #ModelName) ab
DECLARE db_cursor3 CURSOR FOR
SELECT * FROM
(
SELECT [rule]
FROM table_name
WHERE ModelName = #ModelName) cd
OPEN db_cursor3
FETCH NEXT FROM db_cursor3 INTO #rule
WHILE ##FETCH_STATUS = 0
BEGIN
BEGIN
SELECT #SelectList = COALESCE(#SelectList + ', ', '') + '' + #rule + ' AS [GLSegment_' + RIGHT('00' + CAST(#PeriodNumber AS VARCHAR), 3) + ']'
SELECT #SelectList as 'Selectlist'
IF #PeriodNumber < #MaxPeriods
BEGIN
SELECT #WhereList = COALESCE(#WhereList, '') + '(isnull([GLSegment_' + RIGHT('00' + CAST(#PeriodNumber AS VARCHAR), 3) + '],'''') = '''' ) OR '
SELECT #WhereList as 'Wherelist where periodnumber < maxperiods'
END
ELSE IF #PeriodNumber = #MaxPeriods
BEGIN
SELECT #WhereList = COALESCE(#WhereList, '') + '(isnull([GLSegment_' + RIGHT('00' + CAST(#PeriodNumber AS VARCHAR), 3) + '], '''') = '''' )'
SELECT #WhereList as 'Wherelist where periodnumber = maxperiods'
END
SET #PeriodNumber = #PeriodNumber + 1
END
FETCH NEXT FROM db_cursor3 INTO #rule
END
CLOSE db_cursor3
DEALLOCATE db_cursor3
-- build dynamic query
SET #SQL =
'SELECT * into missingfields_' + #ModelName + ' from trans_' + #ModelName + '
WHERE id in
(
SELECT id from
(
SELECT id, ' + #SelectList + '
FROM trans_' + #ModelName + ')A
WHERE ' + #WhereList + '
);
SELECT * from missingfields_' + #ModelName
PRINT #SQL
print 'missingfields_' + #ModelName
EXEC sp_executesql #SQL

An expression of non-boolean expression in dynamic sql concatenated string

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'.

Dynamic sql with CASE expression

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.

SQL Server: Error message on dynamic procecure

I don't have much experience with dynamic procedures so the following was only an attempt.
The only part that is actually dynamic here is the table name which I tried to create by combining the fix part "MOC_" and the variable part #level.
Can someone tell me what I have to change here to make this work ?
The error I get when executing this points to the IF NOT EXISTS part:
Conversion failed when converting the nvarchar value 'IF NOT EXISTS (
SELECT *
FROM MOC_Nav2
WHERE itemID = ' to data type int.
My procedure:
ALTER PROCEDURE [dbo].[MOC_UpdateNav]
#level nvarchar(20),
#itemID int,
#parentID int,
#itemName nvarchar(100),
#sortID int,
#logStatus nvarchar(20),
#lastUpdate nvarchar(50),
#modBy varchar(50)
AS
BEGIN
SET NOCOUNT ON;
BEGIN
DECLARE #sql nvarchar(max)
SET #sql = 'IF NOT EXISTS
(
SELECT *
FROM MOC_' + #level + '
WHERE itemID = ' + #itemID + '
)
INSERT INTO MOC_' + #level + '
(
parentID,
itemName,
sortID,
logStatus,
lastUpdate,
modDate,
modBy
)
SELECT ' + #parentID + ',
' + #itemName + ',
' + #sortID + ',
' + #logStatus + ',
' + #lastUpdate + ',
GETDATE(),
' + #modBy + '
ELSE
UPDATE MOC_' + #level + '
SET parentID = ' + #parentID + ',
itemName = ' + #itemName + ',
sortID = ' + #sortID + ',
logStatus = ' + #logStatus + ',
lastUpdate = ' + #lastUpdate + ',
modDate = GETDATE(),
modBy = ' + #modBy + '
WHERE itemID = ' + #itemID + ''
EXEC(#sql)
END
END
#itemID is an int. Because it is used in the expression, everything else must be converted to a number, including your SQL text.
Convert #itemID (and other numbers) to nvarchar before concatenating it into the query:
SET #sql = N'IF NOT EXISTS
(
SELECT *
FROM MOC_' + #level + '
WHERE itemID = ' + cast(#itemID as nvarchar(30)) + ...