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 :)
Related
I have code :
CourseName + ' ' + isnull(GradeLevel,'')) as CourseName
The result :
Permit Working High 3
How to make result like this :
Permit Working High (3)
CourseName + ' ' +
CASE
WHEN GradeLevel IS NULL THEN ''
ELSE '(' + GradeLevel + ')'
END
AS CourseName
Answered / Solved.
Long story short, I need a stored procedure that would get the data from a few different views and put it into a .CSV file. Easy enough, but me being me, I decided to write something that could get the data from any table one could potentially desire. I decided to go with 2 procedures in the end:
Loop through a table with all the parameters (catalog, schema, table name, export path/file name etc. etc.) and feed it to 2nd stored procedure (in theory it should make it easier to manage in future, if/when different data needs to be exported). This one is fairly straightforward and doesn't cause any issues.
Pick up the column names (which was surprisingly easy - below in case it helps anyone)
select #SQL = 'insert into Temp_Export_Headers ' +
'select COLUMN_NAME ' +
'from [' + #loc_Source_Database + '].information_schema.columns ' +
'where table_name = ''' + #loc_Source_Table + ''''
and
select #Headers = coalesce(#Headers + ',', '') + convert(varchar, Column_Name)
from Temp_Export_Headers
After that, I want to dump all the data from "actual" table into temp one, which in itself is easy enough, but that's where things start to go downhill for me.
select #SQL =
'drop table if exists TempData ' +
'select * ' +
'into TempData ' +
'from [' + #loc_Source_Database + '].' + #loc_Source_Schema + '.' + #loc_Source_Table + ' with (nolock) '
Select * is just temporary, will probably replace it with a variable later on, for now it can live in this state on dev.
Now I want to loop through TempData and insert things I want (everything at the moment, will add some finesse and where clauses in near future) and put it into yet another temp table that holds all the stuff for actual CSV export.
Is there any way to add a self incrementing column to my TempData without having to look for and get rid of the original PK / Identity? (Different tables will have different values / names for those, making it a bit of a nightmare for someone with my knowledge / experience to loop through in a sensible manner, so I'd just like a simple column starting with 1 and ending with whatever last row number is)
#ShubhamPandey 's answer was exactly what I was after, code below is a product of my tired mind on the verge of madness (It does, however, work)
select #SQL =
'alter table TempData ' +
'add Uni_Count int'
select #SQL2 =
'declare #UniCount int ' +
'select #UniCount = 0 ' +
'update tempdata with (rowlock) ' +
'set #UniCount = Uni_Count = #UniCount + 1'
Both versions execute quicker than select * into without any other manipulation. Something I cannot yet comprehend.
Is there a better / more sensible way of doing this? (My reasoning with the loop - there will potentially be a lot of data for some of the tables / views, with most of them executed daily, plan was to export everything on Sat/Sun when system isn't that busy, and have daily "updates" going from last highest unique id to current.)
Looping was a horrible idea. To illustrate just how bad it was:
Looping through 10k rows meant execution time of 1m 21s.
Not looping through 500k rows resulted in execution time of 56s.
Since you are doing a table creation while insertion, you can always go forward with a statement like:
select #SQL =
'drop table if exists TempData ' +
'select ROW_NUMBER() OVER (<some column name>) AS [Id], * ' +
'into TempData ' +
'from [' + #loc_Source_Database + '].' + #loc_Source_Schema + '.' + #loc_Source_Table + ' with (nolock) '
This would create an auto-incrementing index for you in the TempData table
I have a query that looks basically like this, wrapped in a dynamic query to accommodate table names that can change. I got the date functions in the middle converted but it doesn't like the LoadedDateTime and CallPlacedTime at the end. I've tried every conversion and combination of quoting those lines that I can think of. How can I accomplish this?
DECLARE #sql_TotalDialsNewLeads nvarchar(1000) = N'
SELECT COUNT(*)
FROM ' + #tbl_CH + ' ch, ' + #tbl_CL + ' cl, ' + #tbl_DA + ' da
WHERE ch.IDENTITY = cl.IDENTITY
AND cl.CRMID = da.CRMID
AND CallPlacedTime BETWEEN ''' + CONVERT(varchar(30),DATEADD(HOUR,-#TimezoneOffset,#StartDate),126) + '''
AND ''' + CONVERT(varchar(30),DATEADD(HOUR,-#TimezoneOffset,#EndDate),126) + '''
AND Product = ''' + #Product + '''
AND Country = ''' + #Country + '''
AND DATEPART(DayOfYear,DATEADD(HOUR,-#TimezoneOffset,LoadedDateTime))
= DATEPART(DayOfYear,DATEADD(HOUR,-#TimezoneOffset,CallPlacedTime))'
EXECUTE(#sql_TotalDialsNewLeads);
Thanks,
Sean
Try to use sp_executesql with parameters instead of making string to execute manually:
...
AND CallPlacedTime BETWEEN DATEADD(HOUR,-#TimezoneOffset,#StartDate)
AND DATEADD(HOUR,-#TimezoneOffset,#EndDate)
...
and execute it with the following statement:
exec sp_executesql #sql_TotalDialsNewLeads,
N'#StartDate datetime, #EndDate datetime',
#StartDate,#EndDate;
Here is a MSDN guide. Also you can do it for other parameters in your SQL statement.
Instead of using the conversion outside use it inside the dynamic query.
something like this. (Not tested)
DECLARE #sql_TotalDialsNewLeads nvarchar(1000) = N'
SELECT COUNT(*)
FROM ' + #tbl_CH + ' ch, ' + #tbl_CL + ' cl, ' + #tbl_DA + ' da
WHERE ch.IDENTITY = cl.IDENTITY
AND cl.CRMID = da.CRMID
AND CallPlacedTime BETWEEN CONVERT(varchar(30),DATEADD(HOUR,'''+ -#TimezoneOffset +''','''+ #StartDate +'''),126)
AND CONVERT(varchar(30),DATEADD(HOUR,'''+ -#TimezoneOffset +''','''+ #EndDate +'''),126)
AND Product = ''' + #Product + '''
AND Country = ''' + #Country + '''
AND DATEPART(DayOfYear,DATEADD(HOUR,-#TimezoneOffset,LoadedDateTime))
= DATEPART(DayOfYear,DATEADD(HOUR,-#TimezoneOffset,CallPlacedTime))'
EXECUTE(#sql_TotalDialsNewLeads);
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
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.