What is wrong in this?
The error comes from this section;
AND ('''+#searchText+''' = '''' OR (ISNULL(CAST(t1.id as varchar(10)),'''') + '' '' +
ISNULL(CAST(FORMAT(t1.reading_date,#dateformat) as varchar(12)),'''')+'' '' +
ISNULL(t2.description,'''') + '' '' +
ISNULL(t3.equipment_no,'''') + '' '' +
ISNULL(t4.description,'''') + '' '' +
ISNULL(CAST(t1.actual_usage as nvarchar(16)),'''') + '' '' +
ISNULL(t5.uom_code,'''') + '' '' +
ISNULL(CAST(t1.actual_cost as nvarchar(16)),'''') + '' '' +
ISNULL(t6.currency_code,'''') + '' '' +
ISNULL(t1.comment,'''') + '' '' +
ISNULL(CAST(FORMAT(t1.actual_date,#dateformat) as varchar(12)),'''')) LIKE ''%'' '''+#searchText+''' ''%'')
The error:
Msg 102, Level 15, State 1, Line 59
Incorrect syntax near ''.
You can use CONCAT(string1, string2, ...., string_n) instead of doing it manually using + operator. Also, use COALESCE to return column value or empty string. This will simplify the query.
Sample for using CONCAT()
DECLARE #searchText AS VARCHAR(50) = 'SearchMe'
DECLARE #sqlQuery2 AS VARCHAR(5000)
DECLARE #Column1 AS VARCHAR(50) = 'TestValue1'
SET #sqlQuery2 = ' FROM Table
WHERE Column1 = ''' + #Column1 + '''
AND ('''+#searchText+''' = '''' OR (CONCAT(
ISNULL(CAST(t1.id as varchar(10)), '''')
, '' ''
, ISNULL(CAST(FORMAT(t1.reading_date,#dateformat) as varchar(12)), '''')
, '' ''
, ISNULL(t2.description, '''')
, '' ''
, ISNULL(t3.equipment_no, '''')
, '' ''
, ISNULL(t4.description, '''')
, '' ''
, ISNULL(CAST(t1.actual_usage as nvarchar(16)), '''')
, '' ''
, ISNULL(t5.uom_code, '''')
, '' ''
, ISNULL(CAST(t1.actual_cost as nvarchar(16)), '''')
, '' ''
, ISNULL(t6.currency_code, '''')
, '' ''
, ISNULL(t1.comment, '''')
, '' ''
, ISNULL(CAST(FORMAT(t1.actual_date,#dateformat) as varchar(12)), ''''))
)) LIKE ''% ' + #searchText + ' %''
)
ORDER BY someColumn '
select #sqlQuery2
Also noted that LIKE statement string in your code will return syntax error.
Replace the string
LIKE ''%'' ''' + #searchText + ''' ''%''
by this
LIKE ''% ' + #searchText + ' %''
I hope it will help.
Related
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)
How do i use the LTRIM & RTRIM with the following SQL? I need to LTRIM and RTRIM all these fields for leading spaces
UPDATE CORE.WeccoPartyAddress
SET AddressElements = CONTROL.TrimChar(
CASE when COALESCE(Address1,'') != '' THEN Address1 + ', ' ELSE '' END +
CASE when COALESCE(Address2,'') != '' THEN Address2 + ', ' ELSE '' END +
CASE when COALESCE(Address3,'') != '' THEN Address3 + ', ' ELSE '' END +
CASE when COALESCE(Town,'') != '' THEN Town + ', ' ELSE '' END +
CASE when COALESCE(County,'') != '' THEN County + ', ' ELSE '' END +
CASE when COALESCE(Postcode,'') != '' THEN Postcode ELSE '' END, ', '
)
Use like below nested:
UPDATE CORE.WeccoPartyAddress SET AddressElements = rtrim(ltrim(CASE when COALESCE(Address1,'') != '' THEN Address1 + ', ' ELSE '' END + CASE when COALESCE(Address2,'') != '' THEN Address2 + ', ' ELSE '' END + CASE when COALESCE(Address3,'') != '' THEN Address3 + ', ' ELSE '' END + CASE when COALESCE(Town,'') != '' THEN Town + ', ' ELSE '' END + CASE when COALESCE(County,'') != '' THEN County + ', ' ELSE '' END + CASE when COALESCE(Postcode,'') != '' THEN Postcode ELSE '' END))
You don't have to use CASE in your statement
UPDATE CORE.WeccoPartyAddress
SET AddressElements = ISNULL( STUFF (
COALESCE( ', ' + LTRIM( RTRIM(Address1) ) , '') +
COALESCE( ', ' + LTRIM( RTRIM(Address1Address2) ) , '') +
COALESCE( ', ' + LTRIM( RTRIM(Address1Address3) ) , '') +
COALESCE( ', ' + LTRIM( RTRIM(Address1Town) ) , '') +
COALESCE( ', ' + LTRIM( RTRIM(Address1County) ) , '') +
COALESCE( ', ' + LTRIM( RTRIM(Address1Postcode) ) , '')
,1
,2
,''
), '')
If any of Address values is not null you will get string like this: ', Address', then using the function STUFF you replace ', ' at the beginning of the string to get 'Address' as the result.
If all values are null the STUFF function will return NULL which will be replaced with '' by ISNULL function.
I want to check if the columns of a table contain null value and if so assign the 0 value. I had problem because there where UniqueIdentifier column existing. So I change my code to assign '0' value. But now I have a problem when there is DateTime column.
Here is the code:
Select #sql = #sql + 'Case when IsNull(i.[' + Column_Name +
'],''0'') = IsNull(d.[' + Column_name + '],''0'') then ''''
else ' + quotename(Column_Name, char(39)) + ' + '',''' + ' end +'
from information_schema.columns
where table_name = 'Users' and column_name <>'rowguid' and column_name <>'modifieddate'
Another failed attempt:
Select #sql = #sql +
'Case
when IsDate(i.['+Column_Name+']) =1 and IsDate(d.['+Column_Name+']) =1 and IsNull(i.[' + Column_Name + '],1/1/1900) = IsNull(d.[' + Column_name + '],1/1/1900)
then ''''
when IsNull(i.[' + Column_Name + '],''0'') = IsNull(d.[' + Column_name + '],''0'')
then ''''
else ' + quotename(Column_Name, char(39)) + ' + '',''' + ' end +'
from information_schema.columns
where table_name = 'Users' and column_name <>'rowguid' and column_name <>'modifieddate'
Full code:
if #Action = 'U'
BEGIN
Select #sql = #sql +
'Case when IsNull(i.[' + Column_Name +
'],' + CASE DATA_TYPE
WHEN 'int' THEN '0'
WHEN 'bigint' THEN '0'
WHEN 'tinyint' THEN '0'
WHEN 'uniqueidentifier' THEN '''0'''
WHEN 'varchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'nvarchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'date' THEN CHAR(39) + '1/1/1900' + CHAR(39)
WHEN 'datetime' THEN CHAR(39) + '1/1/1900 00:00:00' + CHAR(39)
ELSE ''
END + ') = IsNull(d.[' + Column_name + '],'+
CASE DATA_TYPE
WHEN 'int' THEN '0'
WHEN 'bigint' THEN '0'
WHEN 'tinyint' THEN '0'
WHEN 'uniqueidentifier' THEN '''0'''
WHEN 'varchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'nvarchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'date' THEN CHAR(39) + '1/1/1900' + CHAR(39)
WHEN 'datetime' THEN CHAR(39) + '1/1/1900 00:00:00' + CHAR(39)
ELSE ''
END + ') then ''''
else ' + quotename(Column_Name, char(39)) + ' + '',''' + ' end +'
from information_schema.columns
where table_name = 'Users' and column_name <>'rowguid' and column_name <>'modifieddate'
--Define output parameter
set #ParmDefinition = '#OutString varchar(max) OUTPUT'
--Format sql
set #sql = 'Select #OutString = '
+ Substring(#sql,1 , len(#sql) -1) +
' From dbo.Users i ' --Will need to be updated for target schema
+ ' inner join #tempTrigT d on
i.id = d.id' --Will need to be updated for target schema
--Execute sql and retrieve desired column list in output parameter
exec sp_executesql #sql, #ParmDefinition, #OutString OUT
Here an example how a corresponding CASE might look like -however, it is NOT complete and you might want to extend / redesign it a little:
Select #sql = #sql + 'Case when IsNull(i.[' + Column_Name +
'],' + CASE DATA_TYPE
WHEN 'int' THEN '0'
WHEN 'bigint' THEN '0'
WHEN 'tinyint' THEN '0'
WHEN 'varchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'nvarchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'date' THEN CHAR(39) + '1900-01-01' + CHAR(39)
ELSE ''
END + ') = IsNull(d.[' + Column_name + '],'+
CASE DATA_TYPE
WHEN 'int' THEN '0'
WHEN 'bigint' THEN '0'
WHEN 'tinyint' THEN '0'
WHEN 'varchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'nvarchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'date' THEN CHAR(39) + '1900-01-01' + CHAR(39)
ELSE ''
END + ') then ''''
else ' + quotename(Column_Name, char(39)) + ' + '',''' + ' end +'
from information_schema.columns
Hey I am having a problem with a View I am trying to create I am trying to get the Full Address of a member be Displayed in correlation with the MemberID of my Member Table along with a few other fields in other tables but the FullAddress and MFullAddress are both coming up as NULL Values and I am not sure why hope someone can help. Below is the Code for my View.
SELECT dbo.Member.MemberID, dbo.Member.Title + ' ' + dbo.Member.Forename + ' ' + dbo.Member.Surname AS Fullname, dbo.GetMemberFullAddress(dbo.Member.MemberID) AS FullAddress,
dbo.GetMemberFullMailingAddress(dbo.Member.MemberID) AS MFullAddress, dbo.Lookup_ActionType.Description, dbo.Payment.Amount
FROM dbo.Payment RIGHT OUTER JOIN
dbo.Member ON dbo.Payment.PaymentID = dbo.Member.MemberID RIGHT OUTER JOIN
dbo.Action LEFT OUTER JOIN
dbo.Lookup_ActionType ON dbo.Action.ActionTypeID = dbo.Lookup_ActionType.ActionTypeID ON dbo.Member.MemberID = dbo.Action.MemberID
WHERE (dbo.Member.MemberID = dbo.Member.MemberID)
And here are Both of my Functions Called dbo.GetFullMemberAddress The Mfulladdress function is the same only different fields
USE [ICOM.Database]
GO
/****** Object: UserDefinedFunction [dbo].[GetMemberFullAddress] Script Date: 22/10/2014 11:53:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Richard Glass>
-- Create date: <22/10/2014>
-- Description: <Returns Full Address>
-- =============================================
ALTER FUNCTION [dbo].[GetMemberFullAddress]
-- Add the parameters for the function here
(#MemberID as integer)
RETURNS varchar(250)
AS
BEGIN
DECLARE #AddressLine as varchar(40)
DECLARE #FullAddress as varchar(250)
SET #FullAddress = (SELECT LTRIM(ISNULL(Title + ' ', '') + ForeName + ' ' + Surname) AS FullName FROM Member WHERE MemberID = #MemberID) + CHAR(10)
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
SET #AddressLine = (SELECT Member.AddressLine1 FROM Member WHERE MemberID = #MemberID)
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
SET #AddressLine = (SELECT AddressLine2 FROM Member WHERE MemberID = #MemberID)
IF #AddressLine <> ''
BEGIN
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
END
SET #AddressLine = (SELECT AddressLine3 FROM Member WHERE MemberID = #MemberID)
IF #AddressLine <> ''
BEGIN
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
END
SET #AddressLine = (SELECT Town FROM Member WHERE MemberID = #MemberID)
IF #AddressLine <> ''
BEGIN
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
END
SET #AddressLine = (SELECT PostCode FROM Member WHERE MemberID = #MemberID)
SET #FullAddress = #FullAddress + #AddressLine
RETURN #FullAddress
END
AND
The problem is because concatenetating NULL with anything yields NULL by default. At the start of the function you have:
DECLARE #AddressLine as varchar(40)
DECLARE #FullAddress as varchar(250)
SET #FullAddress = (SELECT LTRIM(ISNULL(Title + ' ', '') + ForeName + ' ' + Surname) AS FullName FROM Member WHERE MemberID = #MemberID) + CHAR(10)
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
And the problem line is:
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
At this point #AddressLine is NULL, therefore you set #FullAddress to NULL.
You can get your full address though in a much less convoluted fashion, something like:
(LTRIM(ISNULL(Title + ' ', '') + ForeName + ' ' + Surname) + ',' +
CASE WHEN ISNULL(AddressLine1, '') = '' THEN '' ELSE AddressLine1 + ',' END +
CASE WHEN ISNULL(AddressLine2, '') = '' THEN '' ELSE AddressLine2 + ',' END +
CASE WHEN ISNULL(AddressLine3, '') = '' THEN '' ELSE AddressLine3 + ',' END +
CASE WHEN ISNULL(Town, '') = '' THEN '' ELSE Town + ',' END +
CASE WHEN ISNULL(PostCode, '') = '' THEN '' ELSE PostCode END
Although seemingly quite verbose, it does not require repeatedly querying the member table. You could then just add this as a computed column:
I would be inclined to add MemberAddress as a computed column to dbo.Member though, something like:
ALTER TABLE dbo.Member
ADD MemberAddress AS
(LTRIM(ISNULL(Title + ' ', '') + ForeName + ' ' + Surname) + ',' +
CASE WHEN ISNULL(AddressLine1, '') = '' THEN '' ELSE AddressLine1 + ',' END +
CASE WHEN ISNULL(AddressLine2, '') = '' THEN '' ELSE AddressLine2 + ',' END +
CASE WHEN ISNULL(AddressLine3, '') = '' THEN '' ELSE AddressLine3 + ',' END +
CASE WHEN ISNULL(Town, '') = '' THEN '' ELSE Town + ',' END +
CASE WHEN ISNULL(PostCode, '') = '' THEN '' ELSE PostCode END;
Would your stored proc be better if the code was just this?
DECLARE #FullAddress as varchar(250)
SELECT FullAddress = LTRIM(ISNULL(Title + ' ', '') + ForeName + ' ' + Surname)
+ CHAR(10)
+ ISNULL(Member.AddressLine1 + CHAR(10),'')
+ ISNULL(Member.AddressLine2 + CHAR(10),'')
+ ISNULL(Member.AddressLine3 + CHAR(10),'')
+ ISNULL(Member.Town + CHAR(10),'')
+ ISNULL(Member.PostCode + CHAR(10),'')
FROM Member
WHERE MemberID = #MemberID
RETURN #FullAddress
I have the following SQL to format a US address into each line for a mailing address but it is rather ugly. Is there a better way to solve this problem or does it have to be this ugly? Also, the problem with this code is that it always ends up with an extra new line at the end.
declare #NL varchar(2);
set #NL = char(13) + char(10);
select
case when rtrim(coalesce(AttentionLine,'') ) != '' then rtrim(AttentionLine ) + #NL else '' end
+ case when rtrim(coalesce(Recipient,'') ) != '' then rtrim(Recipient ) + #NL else '' end
+ case when rtrim(coalesce(AddlAddrLine,'') ) != '' then rtrim(AddlAddrLine ) + #NL else '' end
+ case when rtrim(coalesce(DeliveryAddr,'') ) != '' then rtrim(DeliveryAddr ) + #NL else '' end
+ case when rtrim(coalesce(LastLine,'') ) != '' then rtrim(LastLine ) + #NL else '' end
+ case when rtrim(coalesce(Country,'') ) != '' then rtrim(Country ) + #NL else '' end
as FormattedMailingAddress
from Address
where Id = 1
If your Sql Server Settings are such that NULL + varchar returns NULL (SET CONCAT_NULL_YIELDS_NULL (Transact-SQL)), this can help.
DECLARE #Address TABLE(
ID INT,
AttentionLine VARCHAR(50),
Recipient VARCHAR(50),
AddlAddrLine VARCHAR(50),
DeliveryAddr VARCHAR(50),
LastLine VARCHAR(50),
Country VARCHAR(50)
)
declare #NL varchar(2);
set #NL = char(13) + char(10);
INSERT INTO #Address SELECT 1, NULL, '1', NULL, '2', NULL, '3'
select
case when rtrim(coalesce(AttentionLine,'') ) != '' then rtrim(AttentionLine ) + #NL else '' end
+ case when rtrim(coalesce(Recipient,'') ) != '' then rtrim(Recipient ) + #NL else '' end
+ case when rtrim(coalesce(AddlAddrLine,'') ) != '' then rtrim(AddlAddrLine ) + #NL else '' end
+ case when rtrim(coalesce(DeliveryAddr,'') ) != '' then rtrim(DeliveryAddr ) + #NL else '' end
+ case when rtrim(coalesce(LastLine,'') ) != '' then rtrim(LastLine ) + #NL else '' end
+ case when rtrim(coalesce(Country,'') ) != '' then rtrim(Country ) + #NL else '' end
as FormattedMailingAddress ,
RTRIM(coalesce(AttentionLine + #NL,'')) +
RTRIM(coalesce(Recipient + #NL,'')) +
RTRIM(coalesce(AddlAddrLine + #NL,'')) +
RTRIM(coalesce(DeliveryAddr + #NL,'')) +
RTRIM(coalesce(LastLine + #NL,'')) +
RTRIM(coalesce(Country + #NL,''))
from #Address
where Id = 1
I realize this is an old question, but there is a new solution to this problem: the CONCAT_WS() function, which is new for SQL Server 2017 (it's also available for Azure SQL Database).
SELECT CONCAT_WS (
CHAR(13) + CHAR(10), --Separator
NULLIF(AttentionLine, ''),
NULLIF(Recipient, ''),
NULLIF(AddlAddrLine, ''),
NULLIF(DeliveryAddr, ''),
NULLIF(LastLine, ''),
NULLIF(Country, '')
)
AS FormattedMailingAddress
FROM Address
WHERE Id = 1
NULL values are ignored by the function, which is why NULLIF is used with each argument/parameter in this example. (When the argument/parameter evaluates to NULL, the separator won't be added either). Here's a short blog post with some more details: New For SQL Server 2017: T-SQL Function CONCAT_WS