T-SQL - Show newline constant in results - sql-server

I've been having trouble with a query on a database I'm working with. The database would for instance return 18 results, and the LINQ query in the parent .NET project, would return 27 results. I've found this is down to newlines, as the database was created out of an Excel document.
Is there a way in SQL Server Manangement Studio to show these new line characters in the cells of the results of a query. Just something like printing "\n" on the end of all cells that have this new line character?
I've tried the following query WHERE statements but with no joy:-
AND (FieldName like '%Text String%' + CHAR(10))
AND (FieldName like '%Text String%' + CHAR(13))
AND (FieldName like CHAR(10) + '%Text String%' + CHAR(10))
AND (FieldName like CHAR(13) + '%Text String%' + CHAR(13))
AND (FieldName like CHAR(10) + '%Text String%')
AND (FieldName like CHAR(13) + '%Text String%')
as I read How can I check if an SQL result contains a newline character? with these CHAR(10) and CHAR(13) as ways of testing if there is a new line in the field.
Is there a way to print these new lines in the fields of the results of the query?
UPDATE
As an example:-
The following returns 0 results:-
AND (DrillType = 'Plain Bore')
but the following returns 5 results:-
AND (L3Bore = 'Plain Bore
')
Note, the closing quote and bracket on a new line. Does this make any sense as to why this would be happening?
Thanks in advance!

Related

MultiLine Query in Snowflake Stored Procedure

I am trying to build one stored procedure in snowflake which will
i. Delete existing records from dimension table.
ii. Insert the records into the dimension table from corresponding materialized view.
iii. Once the data is inserted, record the entry into a config table.
First two are running fine, third one is not working, code below
Table DIM_ROWCOUNT
CREATE TABLE ANALYTICSLAYER.AN_MEDALLIA_P.DIM_ROWCOUNT
(
"TABLE_NAME" VARCHAR(500),
"VIEW_NAME" VARCHAR(500),
"TABLE_ROWCOUNT" VARCHAR(500) ,
"VIEW_ROWCOUNT" VARCHAR(500),
"LOADDATE" timestamp
)
The SP has parameter as SRC_TABLE_NAME which should be loaded for column : TABLE_NAME,
VIEW_NAME will be derived inside code.
TABLE_ROWCOUNT and VIEW_ROWCOUNT will be calculated within the code.
I need to have a multi line query for insertion.
How to create the insert statement multiline?
var config_details = `INSERT INTO DBNAME.SCHEMANAME.TABLENAME
SELECT '${VAR_TABLE_NAME}','${VAR_VIEW_NAME}','${VAR_TABLE_ROW_COUNT}','${VAR_VIEW_ROW_COUNT}',getdate();`
var exec_config_details = snowflake.createStatement( {sqlText: config_details} );
var result_exec_config_details = exec_config_details.execute();
result_exec_config_details.next();
Any help in appreciated.
I tend to write complex SQL statements in a javascript SP by appending each line/portion of text to the variable, as I find it easier to read/debug
Something like this should work (though I haven't tested it so there may be typos). Note that to get single quotes round each value I am escaping them in the code (\'):
var insert_DIM_ROWCOUNT = 'INSERT INTO DBNAME.TEST_P.DIM_ROWCOUNT ';
insert_DIM_ROWCOUNT += 'SELECT \'' + SRC_TABLE_NAME + '\', \'' + VIEW_NAME + '\', \'';
insert_DIM_ROWCOUNT += TABLE_ROWCOUNT + '\', \'' + VIEW_ROWCOUNT + '\', ';
insert_DIM_ROWCOUNT += GETDATE();
I then test this to make sure the SQL statement being created is what I want by adding a temporary line of code, after this, to just return the SQL string:
return insert_DIM_ROWCOUNT;
Once I'm happy the SQL is correct I then comment out/delete this line and let the SQL execute.

How to combine feet and inches into one combined column

Combining last name and first name isn't an issue for me - as shown above. The query spits that out fine. However, in this database schema, inches and feet are separated. When I try to combine them as height_feet + ' ' ' + height_inches, I get an error for obvious reasons. What's the best way to combine feet and inches, so that it reads as 6'7 for instance.
I've tried
,height_feet + ''' + height_inches as 'Height'
I've also tried
,concat(cast(height_feet as char), ''' ', cast(height_inches as char), '"')
Neither have helped me get the desired result. All I want is it to read 5'10 if feet is 5 and inches is 10.
SELECT TOP 10
last_name + ', ' + first_name as 'Employee'
,days as 'Days Employed'
,height_feet
,height_inches
,ROUND(sales, 3) as 'Sales'
The right function to do concatenation in MySQL is CONCAT, therefore use it for all your concatenations.
Your problem is just because you are trying to concatenate a reserved char '. In order to concatenate a single quote you need to escape it so you double it.
SELECT
concat(last_name, ', ', first_name) as 'Employee'
,days as 'Days Employed'
,concat(height_feet, '''',height_inches)
,ROUND(sales, 3) as 'Sales'
from ...
where ...
LIMIT 10 -- "TOP 10" is MSSQL syntax
See an example here: http://sqlfiddle.com/#!9/9eecb/102692
EDIT
I just noticed that you may have tagged your question with MySQL when it should be SQL SERVER. Nevertheless since SQL Server has the same function CONCAT the same query will work, see the same example running here: http://sqlfiddle.com/#!18/9eecb/54309

Create word document from SQL Server Management Studio - 1 row per page (email templates for client to view)

Hey there I have a simple EmailTemplate table with three columns:
TemplateName
EmailSubject
EmailContent
I have a client that wants to review all the templates and I'd like to put them into a word document, 1 per page, in the order they are above e.g.
-------------- page 1 --------------
[[TemplateName]]
[[EmailSubject]]
[[EmailContent]]
...
...
...
[[EmailContent]]
-------------- page 2 --------------
[[TemplateName]]
[[EmailSubject]]
[[EmailContent]]
...
...
...
[[EmailContent]]
Does anyone one know of an easy way to do this from SQL Server Management Studio?
Cheers
Rob
Word has a mail merge function that can be used with csv data, I'd recommend that over any attempt to build the entire thing in sql.
I did some more searching, lot's of code solutions but nothing out-of-the-box in SSMS so I did some more fiddling and here's what I did to achieve this:
Set the query output to text
Set the Query -> Query Options -> Text to: no headings and Delimeter | (so it's easy to remove)
Added formatting to the query with Tabs CHAR(9) and Line Breaks CHAR(10) as follows:
SELECT
'Template Name:' + CHAR(9) + CHAR(9) + Name + CHAR(10) + CHAR(10),
'Email Subject:' + CHAR(9) + CHAR(9) + TemplateSubject + CHAR(10) + CHAR(10) + CHAR(10),
'Contents:' + CHAR(10) + CHAR(10),
TemplateContent + CHAR(10) + CHAR(10) + CHAR(10) + CHAR(10) + '------------------------------------' FROM dbo.EmailTemplate
I just copy/paste this contents into Word and then went through and converted the dashed line "----" to page breaks and sent it off to the client to review.

SQL Server Express 2008 R2 - Square brackets in text field not returning results

I've created a simple stored procedure with some default values to enable customised searching of my "MachineModel" database.
As part of the WHERE clause I have something like this:
Model.[ModelName] LIKE '%' + ISNULL(#ModelName, Model.[ModelName]) + '%'
which should allow for partial matches. This works for the majority of models, however if no value is supplied for #ModelName (and therefore the ISNULL resolves to Model.[ModelName]) and the underlying field data contains square brackets, such as "Lenny's Test Model [2010]", then those records records aren't returned by the SProc.
This isn't a huge problem as only 4 models (of about 120,000) actually have square brackets in their names so I could easily change them, however I'm curious to know what's going on and what's the best way to solve this.
Cheers,
Lenny.
You need to replace the leading bracket by [[]
There are 3 characters with meaning in LIKE: % _ [. You don't need to escape the trailing bracket.
For completeness:
Model.[ModelName] LIKE '%' + ISNULL(
--don't do it the other way around!
REPLACE(REPLACE(REPLACE(#ModelName, '[', '[[]), '%', '[%]), '_', '[_]),
Model.[ModelName]) + '%'
Why are you comparing the model with itself in case of null search parameter? This is expensive.
It is also not great practice to mix ands and ors with SQL Server as its expensive, but could be done:
Where (
#ModelName is null OR
(ModelName is not null AND ModelName LIKE '%' + #ModelName + '%')
)
if performance could be a prob, then introducing an if can help, but you do end up duplicating your select
if #ModelName is null
select * from ...
else
select ...
where ModelName LIKE '%' + #ModelName + '%'
You could, but it will upset your dba, build the sql up in code and use sqlparameters and only add the where when this var is not null

SQL Server : LENGTH() inside of REPLICATE()

I have a SQL Server table with the columns Lvl and Title. I need to insert a "-" in front of the title for every character in the Lvl field.
As an example: If Lvl = 111 the title should become --- My Title.
I can only edit the following SQL string. There is no possibility to create other functions or likewise.
SELECT REPLICATE('_', { fn LENGTH(Lvl) }) + ' ' + Title AS Title
FROM Documents
My problem is, that the LENGTH() function doesn't work inside the REPLICATE() function. Does anybody know why or how to solve this problem?
Thank you.
Try this:
SELECT REPLACE(Lvl, '1', '-') + ' ' + Title as Title
FROM Documents
Simply take the Lvl column, and replace all instances of 1 with whatever character you want, then concatenate Title to the end of the result.
Try this. It works fine for me -
select REPLICATE('-',LEN(Lvl)) + ' ' + Title as title from documents

Resources