How to concatenate month number into table name - sql-server-2000

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)

Related

How to make " " values in SQL Server empty/null instead (many columns)?

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

Using SQL Server to replace line breaks in columns with spaces

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

Trying to display a combination of String MM + int DD + int YYYY in SQL Management Studio

I am trying to display a combination of String MM + int DD + int YYYY
in SQL Management Studio. However, i encountered an error like this which says
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the nvarchar value 'November ' to data type int.
My codes are:
SELECT DATENAME(MM, Check_in_date) + ' ' + DAY(Check_in_date) + ' ' +
YEAR(Check_in_date)
FROM Book_Details
Afterwards, i tried casting the Check_in_date into a varchar but encountered an error as well. Any help will be appreciated
You are trying to concatenate a string and an integer.
You need to cast #ID as a string.
try:
SELECT DATENAME(MM, Check_in_date) + ' ' + CAST(DAY(Check_in_date) AS NVARCHAR(2)) + ' ' +
CAST(YEAR(Check_in_date) AS NVARCHAR(4))
FROM Book_Details
if you don't like the space, you may use LTRIM to remove the space
Refer : link
UPDATED on year part

Why variable with nvarchar(max) work incorrect

Currently, I have a function to get list of columns of 1 table with detail attribute. And off course, there are some tables with a lot of columns. So, the output will be over 10.000 characters.
Here I test like this:
declare #aa nvarchar(max)
set #aa = dbo.fnGetColumnList('Table_Name')
print #aa
The result always has around 4000 characters. It looks like the SQL has truncated it.
What I know that when we declare nvarchar(max), SQL will supports up to 2^32-1 (2GB) for this string. But why it just has around 4000 characters?
When I execute like this:
select dbo.fnGetColumnList('Table_Name')
the result is correct.
And here is the code for the function:
-- get column list from table Mapping
ALTER FUNCTION [dbo].[fnGetColumnList] ( #tblName varchar (30))
RETURNS nvarchar(max)
AS
BEGIN
Declare #sql nvarchar(max)
set #sql = ''
SELECT #sql = #sql + case
when CHARINDEX('char', LOWER([DBType])) > 0 then ', ['+[DBColumn]+']' + ' ['+[DBType]+']' + ' ('+convert(varchar(10),[Length])+') NULL' + CHAR(13)
when CHARINDEX('char', LOWER([DBType])) > 0 then ', ['+[DBColumn]+']' + ' ['+[DBType]+']' + ' NULL' + CHAR(13)
ELSE ', ['+[DBColumn]+']' + ' ['+[DBType]+']' + ' NULL' + CHAR(13)
end FROM dbo.Mapping WHERE [DBTable] = #tblName
return #sql
END
Please advance.
This is almost always a variable assignment type problem, as explained in:
For Nvarchar(Max) I am only getting 4000 characters in TSQL?
If it's not that, then it's probably just the settings of Print to display too few characters:
nvarchar(max) still being truncated
Having looked at the updated code, it seems like it's the second issue, your print is truncating as it's not set to show enough characters.
You should see this by running
SELECT LEN(#aa)
You'll get a number larger than 4000, showing the value is held correctly in the variable.
As explained in Microsoft's nvar and nvarchar docs:
A common misconception is to think that with nchar(n) and nvarchar(n), the n defines the number of characters. However, in nchar(n) and nvarchar(n), the n defines the string length in byte-pairs (0-4,000). n never defines numbers of characters that can be stored. This is similar to the definition of char(n) and varchar(n).
There is an option in SQL Management Studio:
Tools > Options... > Query Results > SQL Server > Results to Text > Maximum number of characters displayed in each column

Having some Dynamic SQL issues with INT type

Hello Im using SQL2000 so I build a Dynamic Query and in the last case I have this :
IF (#apepac is not null and #nompac is not null and #month is not null )
SELECT #DynaSQL_1= #DynaSQL_1 + ' AND PACIENTE.apellidos like ''' + #apepac + '%'''+
' AND PACIENTE.nombres like ''' + #nompac + '%'''+
' AND DATENAME(MONTH,honorariotecnologo.fechaestudio) = ''' + #month +'''' +
' AND YEAR(honorariotecnologo.fechaestudio) = '+#year+''
so the parameter #year is declared in this way :
DECLARE #year int,
and the error I get from SQL output is :
Msg 245, Level 16, State 1, Line syntax
43Error to convert the nvarchar value '
What could be wrong?
Thanks!
By the way, Why if the parameter is declared as INT, on the body query it must have to be casted / converted? ...
You have to cast or convert the INT to a NVARCHAR. Google CAST CONVERT TSQL.
You need to cast your #Year as a character value.
Try this:
' AND YEAR(honorariotecnologo.fechaestudio) = ' + CAST(#year AS varchar(10))
You want this to take care of the conversion error...
' AND YEAR(honorariotecnologo.fechaestudio) = '+CAST(#year AS VARCHAR)
You want this if you want to add the single quote to the end of your string.
' AND YEAR(honorariotecnologo.fechaestudio) = '+CAST(#year AS VARCHAR) + ''''