1

i am creating a dynamic query in which i need to put a space in a db field when retrieving the eg is as follows when i give single quotes its not accepting

DECLARE @QUERY VARCHAR(8000)
SET @QUERY='SELECT DATENAME(MM,getdate())+RIGHT(CONVERT(VARCHAR(20),getdate(),107),9)+SUBSTRING(CONVERT (VARCHAR(20),getdate(),100),12,6) + ' '+ RIGHT(CONVERT(VARCHAR(20),getdate(),100),2) AS CurrentDate'
EXECUTE (@QUERY)

the aim is to put a space in between hh:mm and AM/PM

0

3 Answers 3

3

Double up the quotes

DECLARE @QUERY VARCHAR(8000) 
SET @QUERY='SELECT DATENAME(MM,getdate())+RIGHT(CONVERT(VARCHAR(20),getdate(),107),9)+SUBSTRING(CONVERT (VARCHAR(20),getdate(),100),12,6) + '' ''+ RIGHT(CONVERT(VARCHAR(20),getdate(),100),2) AS CurrentDate' 
EXECUTE (@QUERY)

But why is this dynamic? Just run it in line

SELECT
   DATENAME(MM,getdate())+
   RIGHT(CONVERT(VARCHAR(20),getdate(),107),9)+
   SUBSTRING(CONVERT (VARCHAR(20),getdate(),100),12,6) + 
   ' '+
   RIGHT(CONVERT(VARCHAR(20),getdate(),100),2) AS CurrentDate

Or format in the client code...

Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

    DECLARE @QUERY VARCHAR(8000)
    SET @QUERY='SELECT DATENAME(MM,getdate())
+RIGHT(CONVERT(VARCHAR(20),getdate(),107),9)
+SUBSTRING(CONVERT (VARCHAR(20),getdate(),100),12,6) 
+ '' '' 
+ RIGHT(CONVERT(VARCHAR(20),getdate(),100),2) AS CurrentDate'
    EXECUTE (@QUERY) 

To escape the single quotes, use two of them next to each other.

2 Comments

@FilipScript Thank you for the reply its working in sql server but when i call the same using datatable its getting null. i am simply writing it as a procedure.
@FilpScript Sorry it was not the code error actually my length of the varchar was the problem when i increased the length it started performing good. Thanks alot for your help.
0

Another alternative to doubling up quotes (and assuming the need for dynamic SQL is real) is to simply use Char(32)

 DECLARE @QUERY VARCHAR(8000)
    SET @QUERY='SELECT DATENAME(MM,getdate())
+RIGHT(CONVERT(VARCHAR(20),getdate(),107),9)
+SUBSTRING(CONVERT (VARCHAR(20),getdate(),100),12,6) 
+ Char(32)
+ RIGHT(CONVERT(VARCHAR(20),getdate(),100),2) AS CurrentDate'
    EXECUTE (@QUERY) 

1 Comment

It absoluty correct OK, but it is a bit annoying when you often switch betwenn MS-SQLServer and Oracle. The later calls the same function CHR. '' '' works for both and is more readable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.