How to add dynamic SQL delimiter of single quote? - tsql

I am developing a dynamic SQL using SQL Server 2008 T-sql code. So I want to return values that look like "Jan'11".
My code looks something like:
left(datename(month, SGD_SIGNOFF_DATE), 3) + ' + '''' +
' RIGHT(year(SGD_SIGNOFF_DATE), 2) AS MonthYear
But this is not working. Either I get output to look like "Jan11" or I get error messages. What is proper syntax for my solution?

SELECT LEFT(datename(month, SGD_SIGNOFF_DATE), 3) + '''' + RIGHT(year(SGD_SIGNOFF_DATE), 2) AS MonthYear

This should work:
left(datename(month, SGD_SIGNOFF_DATE), 3) + '''' + RIGHT(year(SGD_SIGNOFF_DATE), 2) AS MonthYear

I got it! Here is the code now that works!
left(datename(month, SGD_SIGNOFF_DATE), 3) + '''''''' +
RIGHT(year(SGD_SIGNOFF_DATE), 2) AS MonthYear

Related

Best way to use multiple like statements in XML PATH query

When I use the "Or" operator (Secretary_Job_Title like '%Secretary%' or Secretary_Job_Title like '%Assistant%') I'm returning too many values.
How can I best use Like statement for Secretary and Assistant in the following query? Thanks in advance!!
SELECT STUFF((SELECT ';' + secretary
FROM [HandshakeProd].[dbo].[sp_attysecrel]
WHERE attorney = 'HC\' + Rtrim(p.EMPLOYEE_CODE)
AND secretary_job_title LIKE '%Secretary%'
FOR XML PATH('')), 1, 1, '') AS [Assistants]
Perhaps this is what you want?
SELECT STUFF((SELECT ';' + secretary
FROM [HandshakeProd].[dbo].[sp_attysecrel]
WHERE attorney = 'HC\' + Rtrim(p.EMPLOYEE_CODE)
AND (secretary_job_title LIKE '%Secretary%' OR secretary_job_title LIKE '%Assistant%')
FOR XML PATH('')), 1, 1, '') AS [Assistants]

Dynamic SQL Error with REPLACE Statement

I am trying to create a script that builds a SQL statement dynamically and then executes it.
Here is the string that is built & stored in #strSQL (verified by using PRINT)
UPDATE DNN_RSM_Exams
SET ScoringDates = REPLACE(ScoringDates, '/2015', '/2016')
WHERE SchoolYear = 2015
It executes the variable as follows:
EXECUTE (#strSQL)
However I get the following error:
Conversion failed when converting the nvarchar value 'UPDATE DNN_RSM_Exams SET ScoringDates = REPLACE(ScoringDates, '/' to data type int.
It seems to terminate the EXECUTE when it hits the first forward-slash (/). I tried escaping it using a double slash (//), an open bracket ([), and a backslash (\). None if it worked.
Can anyone help me please?
UPDATE #01: 8/17/15
Sorry if I didn't give enough information initially...
ScoringDates is an NVARCHAR(MAX) field.
The Code that builds the SQL Statement is:
SET #strSQL = 'UPDATE ' + #strTableName +
' SET ScoringDates = REPLACE(ScoringDates, ''/' + LTRIM(RTRIM(STR(#intSchoolYear_CopyFrom + 1))) + ''', ''/' + LTRIM(RTRIM(STR(#intSchoolYear_CopyFrom + 2))) + ''')' +
' WHERE SchoolYear = ' + LTRIM(RTRIM(STR(#intSchoolYear_CopyTo)))
ScoringDates is a string based field that holds data in an INI-like formatted string. I want to change the year portion of ANY date found in the string, but I want to avoid accidental changes of any other numbers that may match. So I am specifically looking to replace "/YYYY" with a different "YYYY" value. The "/" preceding the year value is to ensure that what is being preplaced is the YEAR and not another numeric value within the string.
UPDATE #02: 8/18/15
So I am completely flabbergasted...after banging my head on this script for hours yesterday, I went home defeated. Come in today, start up my PC and run the script again so I can see the error message again...and it worked!
I've never come across this with SQL Management Studio, but it is possible that SQL Management Studio somehow lost it's marbles yesterday and needed a reboot? I thought the SQL was process by the server directly. Could it be that some is processed by the studio first before handing it off to the server and if the studio had "issues" then it would cause strange errors?
In any case, thank you so much guys for your input, I am sorry that it was a wheel spinner. It never occurred to me that a reboot would fix my issue, I just assumed my code was wrong.
You want to replace '/ with ''
So your set statement will be something like...
SET #strSQL = 'UPDATE DNN_RSM_Exams
SET ScoringDates = REPLACE(ScoringDates, ''2015'', ''2016'')
WHERE SchoolYear = 2015'
EDIT:
How is your code different than this below? (I will edit this again and clean it up after. Code just won't fit into comments)
DECLARE #TableName TABLE (ScoringDates VARCHAR(100), SchoolYear INT)
DECLARE #strTableName VARCHAR(MAX)
DECLARE #intSchoolYear_CopyFrom VARCHAR(MAX)
DECLARE #intSchoolYear_CopyTo VARCHAR(MAX)
SET #strTableName = '#TableName'
SET #intSchoolYear_CopyFrom = '2009'
SET #intSchoolYear_CopyTo = '2010'
DECLARE #strSQL VARCHAR(MAX)
SET #strSQL = 'DECLARE #TableName TABLE (ScoringDates VARCHAR(100), SchoolYear INT); UPDATE ' + #strTableName +
' SET ScoringDates = REPLACE(ScoringDates, ''/' + LTRIM(RTRIM(STR(#intSchoolYear_CopyFrom + 1))) + ''', ''/' + LTRIM(RTRIM(STR(#intSchoolYear_CopyFrom + 2))) + ''')' +
' WHERE SchoolYear = ' + LTRIM(RTRIM(STR(#intSchoolYear_CopyTo)))
PRINT #strSQL
EXECUTE (#strSQL)

Append an integer to a string as a string

Trying to do something like this:
select 'Setup for Car ' + CAST(varchar(50), #CarID) + ' for user ' + CAST(varchar(5), #UserID)
doesn't work, not sure what the syntax would be then for T-SQL. I've hunted around, have not found it yet.
You can user either of these:
select 'Setup for Car ' + Convert(varchar(50), #CarID) + ' for user ' + Convert(varchar(5), #UserID)
OR
select 'Setup for Car ' + CAST(#CarID as varchar(50)) + ' for user ' + CAST(#UserID as varchar(5))
You are using CAST wrong. It should be
CAST(#Variable AS WhatYouAreCastingTo)
Here is a fiddle showing this
Remember, MSDN is your friend :)

TSQL - Join text fields to one big text

I have a table like this:
ID text_1 text_2 text_3
12 some text some more even more
I need it to be put it to be put to one string so it comes out like
some text\n\nsome more\n\neven more
Now I know that \n is something else in TSQL but I can't remember what, maybe CHAR(13).
Anyone know to archive this?
This query will return the string you want:
SELECT text_1 + '\n\n' + text_2 + '\n\n' + text_3
FROM myTable
If you want a line break character you will indeed need to use CHAR(13) and for a line feed CHAR(10), in a similar manner:
SELECT text_1 + CHAR(13) + CHAR(10) + text_2 + CHAR(13) + CHAR(10) + text_3
FROM myTable
As #Adam Robinson comments, if the text_x fields are of type TEXT or NTEXT you will need to convert them first.

TSQL -- Inserting Dates Into Dynamic SQL

Consider the following TSQL:
SET #WhereClause1 = 'where a.Date > ' + #InvoiceDate
I get a date/string conversion error. #InvoiceDate is a datetime variable. What is the right syntax?
This might work.
SET #WhereClause1 = 'where a.Date > ''' + convert(varchar, #InvoiceDate) + ''''
although an error will be raised if the value is null.
This will work:
SET #WhereClause1 = 'where a.Date > ''' + cast(#InvoiceDate as varchar(100)) + ''''
Since your composing query as a string first, then I think you need to convert #InvoiceDate to a string with something like this. http://www.databasejournal.com/features/mssql/article.php/10894_2197931_1/Working-with-SQL-Server-DateTime-Variables-Part-Two---Displaying-Dates-and-Times-in-Different-Formats.htm
... and you will probably need to enclose date strings in quotes.
It would probably actually be better to construct the date string in the calling routine because you should be checking there for null values and maybe other validations.
EXEC sp_executesql N'SELECT * FROM Orders WHERE a.Date > #date',
N'#date datetime',
#date = #InvoiceDate