I have a table with some 150 columns, and I haven't the faintest clue how to remove these " " values. I've seen some solutions for single columns, but since I have so many I would like a solution that does it for every column... not sure if that's possible?
I tried:
USE master
UPDATE [master].[dbo].[csvimport]
SET value = NULL
WHERE value = " "
From what I found researching, but it tells me:
Msg 207, Level 16, State 1, Line 2
Invalid column name 'value'.
Msg 207, Level 16, State 1, Line 2
Invalid column name ' '.
I've seen:
SELECT NULLIF(null_column, 0) AS null_column
FROM [master].[dbo].[csvimport]
But this only works for one column at a time. I'd rather not do this 150 times...
This will result in a bunch of SQL statements to run. or you can cursor it. I was a little confused with your search term of " " which isn't tsql logic.
declare #tablename varchar(100) ='[Enter your table name]'
select 'Update '+ #tablename + ' set ' + quotename(column_name) + '=null where '+ quotename(column_name) + '='' '''
from INFORMATION_SCHEMA.columns
where TABLE_NAME = #tablename
to help you understand this query run this. The rest is dynamically building SQL around it:
select quotename(column_name),*
from INFORMATION_SCHEMA.columns
Related
DECLARE #listofelements NVARCHAR(4000)
SELECT #listofelements = COALESCE(#listofelements + ',', '') + '[' + OBJECT_SCHEMA_NAME(v.object_id) + '].[' + v.name +']' FROM sys.views as v
PRINT #listofelements
UPDATE [database].[dbo].[Table1] SET [Total_text] = #listofelements
The code above till the PRINT statement works fine. The print statement gives me a large text string which is what I want. This textstring looks to be generated on the fly. However, if I want to update a table in my database with this value #listofelements then it updates nothing. How come that #listofelements which is generated by the script is not able to update my Table1. It has nothing to do with the length of the string of type. It doesn't give an error, it just doesn't update. It looks like #listofelements is empty while on the other hand I can print it. Note: I ran all 5 lines at the same time.
I am working on a report where I need to provide a summary of notes for particular "activities/tasks".
Since the activity can accept multiple notes, I have to search for all the notes related to that activity. I then order it by date (new to old), and concatenate them with some other strings as such:
[Tom Smith wrote on 9/23/2016 1:21 pm] Client was out of office, left message. [Jane Doe wrote on 9/21/2016 3:24 pm] Client called asking about pricing.
The data comes from replicated tables of our on-premise CRM system, and I'm using SQL Server 2012. The tables I'm using are: AnnotationBase (contains the notes), ActivityPointerBase (contains the activities/tasks), and SystemUserID (to lookup usernames). Due to Data mismatch, I have to do some converting of the data types so that I can concatenate them properly, so that's why there's a lot of CAST and CONVERT. In addition, not all Activities have a NoteText associated with them, and sometimes the NoteText field is NULL, so I have to catch and filter the NULLs out (or it'll break my concatenated string).
I have written the following query:
DECLARE #Notes VarChar(Max)
SELECT
( SELECT TOP 5 #Notes = COALESCE(#Notes+ ', ', '') + '[' + CONVERT(varchar(max), ISNULL(sUB.FullName, 'N/A')) + ' wrote on ' + CONVERT(varchar(10), CAST(Anno.ModifiedOn AS DATE), 101) + RIGHT(CONVERT(varchar(32),Anno.ModifiedOn,100),8) + '] ' + CONVERT(varchar(max), ISNULL(Anno.NoteText, '')) --+ CONVERT(varchar(max), CAST(ModifiedOn AS varchar(max)), 101)--+ CAST(ModifiedOn AS varchar(max))
FROM [CRM_rsd].[dbo].[AnnotationBase] AS Anno
LEFT OUTER JOIN [CRM_rsd].[dbo].[systemUserBase] AS sUB
ON Anno.ModifiedBy = sUB.SystemUserId
WHERE Anno.ObjectId = Task.ActivityId--'0B48AB28-C08F-419A-8D98-9916BDFFDE4C'
ORDER BY Anno.ModifiedOn DESC
SELECT LEFT(#Notes,LEN(#Notes)-1)
) AS Notes
,Task.*
FROM [CRM_rsd].[dbo].[ActivityPointerBase] AS Task
WHERE Task.Subject LIKE '%Project On Hold%'
I know the above method is probably not very efficient, but the list of "Projects On Hold" is rather small (less than 500), so performance isn't a priority. What is a priority is to be able to get a consolidated and concatenated list of notes for each activity. I have been searching all over the internet for a solution, and I have tried many different methods. But I get the following errors:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '='.
Msg 102, Level 15, State 1, Line 10
Incorrect syntax near ')'.
I envision two possible solutions to my problem:
My subquery errors are fixed or
Create a "view" of just the concatenated NotesText, grouped by ActivityId (which would work as a key), and then just query from that.
Yet even though I'm pretty sure my ideas would work, I can't seem to figure out how to concatenate a column and group at the same time.
What you are trying to do is display the records from one table (in your case ActivityPointerBase) and inside you want to add a calculated column with information from multiple records from another table (in your case AnnotationBase) merged in the rows.
There are multiple ways how you could achieve this that are different in terms of performance impact:
Option 1. You could write a scalar function that would receive as parameter the id of the task and would inside select the top 5 records, concatenating them in a procedural fashion and returning a varchar(max)
Option 2: You could use a subquery in combination with the FOR XML clause.
SELECT
SUBSTRING(
CAST(
(SELECT TOP 5 ', ' +
'[' + CONVERT(varchar(max), ISNULL(FullName, 'N/A')) +
' wrote on ' +
CONVERT(varchar(10), CAST(ModifiedOn AS DATE), 101) +
RIGHT(CONVERT(varchar(32),ModifiedOn,100),8) + '] ' +
CONVERT(varchar(max), ISNULL(NoteText, ''))
FROM [CRM_rsd].[dbo].[AnnotationBase] AS Anno
LEFT OUTER JOIN [CRM_rsd].[dbo].[systemUserBase] AS sUB ON Anno.ModifiedBy = sUB.SystemUserId
WHERE Anno.ObjectId = Task.ActivityId
ORDER BY Anno.ModifiedOn DESC
FOR XML PATH(''),TYPE
) AS VARCHAR(MAX)
),3,99999) AS Notes
,Task.*
FROM [CRM_rsd].[dbo].[ActivityPointerBase] AS Task
WHERE Task.Subject LIKE '%Project On Hold%'
What here happens is that by using the construct inside the CAST() we fetch the top 5 lines and make SQL server produce an XML with no element names, resulting in concatenation of the element values, we add comma as separator. Then we convert the XML to varchar(max) and remove the initial separator before the first record.
I prefer option 2, it will perform much better then using a scalar function.
I have a large table of data where some of my columns contain line breaks. I would like to remove them and replace them with some spaces instead.
Can anybody tell me how to do this in SQL Server?
Thanks in advance
SELECT REPLACE(REPLACE(#str, CHAR(13), ''), CHAR(10), '')
This should work, depending on how the line breaks are encoded:
update t
set col = replace(col, '
', ' ')
where col like '%
%';
That is, in SQL Server, a string can contain a new line character.
#Gordon's answer should work, but in case you're not sure how your line breaks are encoded, you can use the ascii function to return the character value. For example:
declare #entry varchar(50) =
'Before break
after break'
declare #max int = len(#entry)
; with CTE as (
select 1 as id
, substring(#entry, 1, 1) as chrctr
, ascii(substring(#entry, 1, 1)) as code
union all
select id + 1
, substring(#entry, ID + 1, 1)
, ascii(substring(#entry, ID + 1, 1))
from CTE
where ID <= #max)
select chrctr, code from cte
print replace(replace(#entry, char(13) , ' '), char(10) , ' ')
Depending where your text is coming from, there are different encodings for a line break. In my test string I put the most common.
First I replace all CHAR(10) (Line feed) with CHAR(13) (Carriage return), then all doubled CRs to one CR and finally all CRs to the wanted replace (you want a blank, I put a dot for better visability:
Attention: Switch the output to "text", otherwise you wont see any linebreaks...
DECLARE #text VARCHAR(100)='test single 10' + CHAR(10) + 'test 13 and 10' + CHAR(13) + CHAR(10) + 'test single 13' + CHAR(13) + 'end of test';
SELECT #text
DECLARE #ReplChar CHAR='.';
SELECT REPLACE(REPLACE(REPLACE(#text,CHAR(10),CHAR(13)),CHAR(13)+CHAR(13),CHAR(13)),CHAR(13),#ReplChar);
I have the same issue, means I have a column having values with line breaks in it. I use the query
update `your_table_name` set your_column_name = REPLACE(your_column_name,'\n','')
And this resolves my issue :)
Basically '\n' is the character for Enter key or line break and in this query, I have replaced it with no space (which I want)
Keep Learning :)
zain
I like to concatenate the month number with a text to build table names. For example, I am trying to retreive data for May 2013, I would like to select from webproxylog5.
The following script
select *
from webproxylog + '' + cast(month(dateadd(m,-2,getdate())) as varchar(2)) + ''
will result in the following error messsage:
Msg 170, Level 15, State 1, Line 4
Line 4: Incorrect syntax near '+'.
What is wrong with this syntax?
Thank you,
Seyed
you would need to build dynamic sql for that,
something like
declare #sql varchar(200)
set #sql= 'select * from webproxylog + ' + cast(month(dateadd(m,-2,getdate())) as varchar(2))
exec(#sql)
CASE WHEN PFW_Access__c = 1
THEN 'New Employee (' + New_Employee_Name__c + ') needs PFW Access'
ELSE ''
END AS PFWAccessDesc,`
The line above is just one of many lines in my select statement. It outputs correctly with New Employee (name) needs PFW Access. What I'm trying to do is to add another field to the output Description_Short__c but when I tried to add it to the statement I receive an error. I'm not sure how to add it in to the statement to show in the output.
is this waht you are after?
CASE WHEN PFW_Access__c = 1
THEN 'New Employee (' + ISNULL(New_Employee_Name__c,'') + ') needs PFW Access '
+ISNULL(Description_Short__c,'')
ELSE ''
END AS PFWAccessDesc,
If I remember correctly from a previous question, Description_Short__c is a text field in your database. If you're trying to do just about anything w/ this column, you're going to have to use cast(Description_Short__c as varchar(max)) instead of Description_Short__c.