Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when using single quote with sp_executesql

I have the following SQL statement so that I can script out view creation using if not exists with sp_executesql but the statement is giving me errors due to the single quotes around 1 in my last where statement. Is there any way around this?

    IF NOT EXISTS (SELECT * FROM SYS.objects WHERE NAME = 'vw_JeopardyAlertDetails' AND    TYPE = 'V')
    EXEC sp_executesql @statement = N'CREATE VIEW [dbo].[vw_JeopardyAlertDetails]
AS 
    SELECT Main.TicketNumber, TS.TicketStateDesc, Main.ApptEnd, ISNULL(C.FirstName, '') AS FirstName, ISNULL(C.LastName, '') AS LastName, ISNULL(Main.CustomerID, '') 
                   AS CustomerID, Main.ApptID, Main.ID, Main.TicketType
    FROM  (SELECT s.TicketState, s.TicketID AS ID, s.ApptEnd, dbo.Ticket.TicketNumber, dbo.Ticket.TimeOpened, dbo.Ticket.CreatedBy, dbo.Ticket.ReportedBy, 
                                  dbo.Ticket.ModifiedBy, dbo.Ticket.ChangedBy, dbo.Ticket.Priority, dbo.Ticket.ServingArea, dbo.Ticket.StructureLink, dbo.Ticket.CustomerID, 
                                  dbo.Ticket.TicketCategory, dbo.Ticket.TicketCode, s.ApptStart, s.TicketType, s.CanReschedule, ISNULL(s.ID, 0) AS ApptID
                   FROM   dbo.Schedule AS s INNER JOIN
                                  dbo.Ticket ON s.TicketID = dbo.Ticket.ID
                   WHERE (s.TicketState IN
                                      (SELECT DISTINCT TicketState
                                       FROM   dbo.AlertJeopardyTicketState
                                       WHERE (IsJeopardyState = '1'))) AND (s.ApptEnd >= CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 111) + ' ' + dbo.GetJeopardyStartTime())) 
                                  AND (s.ApptEnd <= GETDATE())) AS Main LEFT OUTER JOIN
                   dbo.Customer AS C ON Main.CustomerID = C.ID LEFT OUTER JOIN
                   dbo.TicketStatus AS TS ON Main.TicketState = TS.ID
    GO' ;
    ELSE PRINT N'vw_JeopardyAlertDetails ALREADY EXISTS'
GO
like image 514
ghoston3rd Avatar asked Feb 22 '26 17:02

ghoston3rd


1 Answers

You'll need to double up those quotes in your Sql @statement, e.g.

ISNULL(C.FirstName, '')

needs to be

ISNULL(C.FirstName, '''')

Simplified fiddle here

like image 188
StuartLC Avatar answered Feb 25 '26 08:02

StuartLC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!