我写了一个SQL查询。但这给了我一个错误。
DECLARE @Delimiter Char(1)
SET @Delimiter = CHAR(9)
EXEC MSDB.dbo.sp_Send_DBMail
@profile_name = 'K2MailSetup',
@Recipients='test@xyz.com',
@Subject='Extraction Report',
@Body='Hi',
@Query='set nocount on;
Select Coalesce(replace(replace(A.[type], char(10), ''''), char(13), ''''),'''') as Type,
try_convert(xml, col).value(''(/collection/object/fields/field/value)[1]'', ''varchar(3)'')
from (select col= Coalesce(replace(replace(A.[business_line], char(10), ''''), char(13), ''''),'''')
FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A'
错误状态
第15层状态1线的消息102
'/'附近的语法不正确。
答案 0 :(得分:1)
我在这里发现了2个问题。
- 您的子查询未正确关闭
- 您的报价未终止属性
Declare @Query as nvarchar(1000)
Set @Query='set nocount on;
set QUOTED_IDENTIFIER on;
Select try_convert(xml, Coalesce(replace(replace(A.[business_line], char(10), '''''''')
, char(13), ''''''''),''''''''))
.value(''(/collection/object/fields/field/value)[1]'', ''varchar(3)'')
, Coalesce(replace(replace(A.[type], char(10), ''''''''), char(13), ''''''''),'''''''') as [Type]
from [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A;'
答案 1 :(得分:1)
动态SQL的窍门是在尝试使其动态化之前确保SQL能够正常工作。
您的查询需要进行多次调整才能用作基本SQL查询:
set nocount on;
select coalesce(replace(replace(A.[type], char(10), ''''), char(13), ''''),'''') as Type
, try_convert(xml, col).value('(/collection/object/fields/field/value)[1]', 'varchar(3)')
from (
select col = coalesce(replace(replace([business_line], char(10), ''''), char(13), ''''),''''), Type
FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS]
) A;
然后直到那时,通过将所有单引号加倍将其转换为动态SQL:
declare @Query as nvarchar(1000) = 'set nocount on;
select coalesce(replace(replace(A.[type], char(10), ''''), char(13), ''''),'''') as Type
, try_convert(xml, col).value(''(/collection/object/fields/field/value)[1]'', ''varchar(3)'')
from (
select col = coalesce(replace(replace([business_line], char(10), ''''), char(13), ''''),''''), Type
FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS]
) A;'
exec(@Query);