How do I correctly implement quotename in SQL Server? - sql

Background Info:
I have a stored procedure that is populating an SSRS report. The SSRS report is ran and exported as a CSV. It is then opened as textfile and ran through a 3 party vendor application.
The output of the text book should look like this:
lid, status, i_flag,Count, pDate, iDate
62558633,"Text Value","08/16",11,"08/16","08/16"
78013526,"Text Value","",,"08/16""08/16"
My results look like this:
lid, status, i_flag,Count,pDate,iDate
19007442,"'Dir,MgmtII'",'',2,'','02/16'
17343623,'Text','',0,'11/15','02/16'
Now the code that I'm using is:
SELECT
quotename(isnull(i_flag,''''), '''') as i_flag,
isnull(lid, 0) as lid,
quotename(isnull(status,''''), '''') as status,
isnull(Count, 0) as Count,
quotename(isnull(p_Date,''''), '''') as p_Date,
quotename(isnull(i_Date,''''), '''') as i_Date
FROM
#Table
Any ideas on how I can fix this. Been stumped on this for a bit. Thanks.

If I'm understanding your question correctly (which I'm quite possibly not), I think you want:
SELECT
QUOTENAME(ISNULL(i_flag,''), '"') AS i_flag,
ISNULL(lid, 0) AS lid,
QUOTENAME(ISNULL([status],''), '"') AS [status],
ISNULL([Count], 0) AS [Count],
QUOTENAME(ISNULL(p_Date,''), '"') AS p_Date,
QUOTENAME(ISNULL(i_Date,''), '"') AS i_Date
FROM
#Table
It sounds like you have some values in fields which you wish to wrap in double quotes " for the purpose of exporting to CSV, plus in some cases the values in these fields might be NULL.
My suggestion above handles this by first using ISNULL to replace any NULL values with an empty string and then using QUOTENAME to wrap the resultant value in double quotes.
The crucial differences to your posted code are:
When using ISNULL I replace the NULL with an empty string '' instead of a string containing a single quote character '''' (two consecutive single quotes within a string represent an escaped literal single quote character)
When using QUOTENAME to wrap the values in double quotes, I specify a string containing a double quote '"' in the second parameter, instead of a string containing a single quote character ''''.
I hope that helps you - if you're still having problems, perhaps you could provide some sample rows from your #Table temp table and the output you're expecting from the query so people can help you further.
As an aside, it's not good practice to use SQL reserved keywords like status or count as column names or aliases, but if you must, I'd recommend enclosing them in brackets (i.e. [status]) for readability (especially in SSMS or any IDE with SQL syntac highlighting or colour-coding) as I have done above.

Related

Oracle RegEx in a Cast Procedure

I have a Cast Procedure for a table with "raw" data. Any time a record comes from any of our locations into the raw table, my procedure "cleans" the data and loads it into a new table. The original raw table is all varchars and my procedure converts date and number fields to the proper data types. From the clean table, a Java program selects any new records on a daily basis and FTPs them off in a file to another dept. Have just learned that a few of the fields accept input from users and on a rare occasion, someone uses a pipe in what they input. A pipe symbol happens to be the delimiter that the other dept is using and whenever a pipe shows up in the middle of a field, it throws a wrench on their end.
I've never used REGEX or REGEXP_REPLACE in Oracle before. There are only three fields where the users can input data - MISTINTCOMMENT, PALETTE, COLORID. How do I use REGEX or REGEXP_REPLACE to replace any pipes with a space? Do I want to do it on each field? Or is this something I should "wrap around" the entire statement (in case there's a field I missed where someone might be able to input a pipe)?
Here is the portion of the procedure where the Values are cleaned and inserted into new table. How to best use RegEx with this?
VALUES (CASE
WHEN THECOSTCENTER IS NOT NULL
THEN THECOSTCENTER
ELSE (SUBSTR(TRIM(THESENDING_QMGR), -6))
END,
CASE
WHEN THESTORENBR = '0' AND (SUBSTR(THESENDING_QMGR, 1, 5) = 'PDPOS')
THEN TO_NUMBER(SUBSTR(THESENDING_QMGR, 8, 4))
WHEN THESTORENBR = '0' AND (SUBSTR(THESENDING_QMGR, 1, 8) = 'PROD_POS')
THEN TO_NUMBER(SUBSTR(THESENDING_QMGR, 9, 4))
ELSE TO_NUMBER(NVL(THESTORENBR,'0'))
END,
TO_NUMBER(NVL(THECONTROLNBR,'0')), TO_NUMBER(NVL(THELINENBR,'0')), THESALESNBR, TO_NUMBER(NVL(THEQTYMISTINT,'0')), THEREASONCODE, THEMISTINTCOMMENT,
THESIZECODE, THETINTERMODEL, THETINTERSERIALNBR, TO_NUMBER(NVL(THEEMPNBR,'0')), TO_DATE(THETRANDATE,'YYYY-MM-DD'), THETRANTIME, THECDSADLFLD,
THEPRODNBR, THEPALETTE, THECOLORID, TO_DATE(THEINITTRANDATE,'YYYY-MM-DD'), TO_NUMBER(NVL(THEGALLONSMISTINTED,'0'),'999999999.99'), THEUPDATEEMPNBR,
TO_DATE(THEUPDATETRANDATE,'YYYY-MM-DD'), TO_NUMBER(NVL(THEGALLONS,'0'),'999999999.99'), THEFORMSOURCE, THEUPDATETRANTIME, THESOURCEIND,
TO_DATE(THECANCELDATE,'YYYY-MM-DD'), THECOLORTYPE, TO_NUMBER(NVL(THECANCELEMPNBR,'0')), TO_BOOLEAN(THENEEDEXTRACTED), TO_BOOLEAN(THEMISTINTMQXTR),
THEDATASOURCE, THETRANGUID, TO_NUMBER(NVL(THETERMNBR,'0')), TO_NUMBER(NVL(THETRANNBR,'0')), TO_NUMBER(NVL(THETRANID,'0')), THEID, THETINTABLESALESNBR,
TO_NUMBER(NVL(THERETURNQTY,'0')), THECREATED_TS, THEXMIT_GUID, THESENDING_QMGR, THEMSG_ID, THEPUT_TS,
THEBROKER_NAME, THECHECKSUM);
If you have to use a REGEXP_REPLACE to replace pipes, escape them:
REGEXP_REPLACE(x, '\|', ' ')
This is useful to know when your more complex expressions include a pipe.
In this case, REPLACE that performs literal text search and replace will suffice:
REPLACE(x, '|', ' ')

Getting unwanted data in select statement of NChar column

On running the below query:
SELECT DISTINCT [RULE], LEN([RULE]) FROM MYTBL WHERE [RULE]
LIKE 'Trademarks, logos, slogans, company names, copyrighted material or brands of any third party%'
I am getting the output as:
The column datatype is NCHAR(120) and the collation used is SQL_Latin1_General_CP1_CI_AS
The data is inserted with an extra leading space in the end. But using RTRIM function also I am not able to trim the extra space. I am not sure which type of leading space(encoded) is inserted here.
Can you please suggest some other alternative except RTRIM to get rid of extra white space at the end as the Column is NCHAR.
Below are the things which I have already tried:
RTRIM(LTRIM(CAST([RULE] as VARCHAR(200))))
RTRIM([RULE])
Update to Question
Please download the Database from here TestDB
Please use below query for your reference:
SELECT DISTINCT [RULE], LEN([RULE]) FROM [TestDB].[BI].[DimRejectionReasonData]
WHERE [RULE]
LIKE 'Trademarks, logos, slogans, company names, copyrighted material or brands of any third party%'
You may have a non-breaking space nchar(160) inside the string.
You can convert it to a simple space and then use the usual trim function
LTRIM(RTRIM(REPLACE([RULE], NCHAR(160), ' ')))
In case of unicode space
LTRIM(RTRIM(REPLACE(RULE, NCHAR(0x00A0), ' ')))
I guess this is what you are looking for ( Not sure ) . Make a try with this approach
SELECT REPLACE(REPLACE([RULE], CHAR(13), ''), CHAR(10), '')
Reference links : Link 1 & Link 2
Note: FYI refer those links for better understanding .
change the type nchar into varchar it will return the result without extra space

Concatenating a space in CDS views

As of ABAP 7.40 SP5 I can use the CONCAT function to combine two fields in my CDS view select list. It's limited to two parameters but I can work around that by chaining this function to combine multiple fields or build larger strings. What I can't do this way is combine two fields with a space separating them. When I do this:
define view Z...
as select from but000 as bp
{
concat( concat( bp.name_first, ' '), bp.name_last )
}
The space ' ' is silently trimmed from the resulting string. How can I separate fields with a space?
ABAP 7.50
ABAP 7.50 will include the CONCAT_WITH_SPACE function that addresses this problem. With that function the example above can be written simply as:
CONCAT_WITH_SPACE( bp.name_first, bp.name_last, 1 )
With the 1 referring to the number of spaces that are to be inserted between the two arguments.
7.50 also introduces other string functions like INSTR, LEFT, LENGTH, LTRIM, RIGHT, RPAD and RTRIM. 7.51 looks set to add LOWER and UPPER to that list.
ABAP 7.40
There is no clean way to accomplish the same in this release. The only way seems to be to concatenate the two fields with a dummy string that encloses the space in a character group that won't appear in the fields that are being selected. After combining you can then remove those characters from the result, leaving just the space. I've taken this approach from Christian Seitel on the SAP forums.
REPLACE(CONCAT( CONCAT( bp.name_first, '|-| |-|'), bp.name_last),'|-|', '')
This works because it will process this string as follows:
name_first|-| |-|
name_first|-| |-|name_last
name_first name_last
If you are still struggling with a <7.50 version. You can try:
concat(concat("first_string",(' ')), "second_string")
I hope it helps.

insert string with " ' " to oracle

Hey I'm using oracle DB with Iron Python and I'm having trouble with strings that contains the char " ' " like in Mc'donalds. (I know it is looking for the closing ' )
The string is accepted from the user input and I want to add it to my DB as it is, meaning without omitting or changing any character.
How can I do it?
Try using the "q" (quote) function:
INSERT INTO restaurantTable (name)
VALUES (q'[O'Reilly and Conway's Irish Pub]');
You can also double-up the single apostrophes (O''Reilly and Conway''s Irish Pub). But in your case you'd have to parse them out, so either using the quote function or query parameters would work the best.
For more information: Q-quote operator introduced in Oracle 10g
Taken from PL/SQL, how to escape single quote in a string?
You can do it either using Q quoting like
q'[insert into MY_TBL (Col) values('ER0002')]';
OR you can use two quotes to denote a single quote
'insert into MY_TBL (Col) values(''ER0002'')';

SQL Query: data with comma

Im using sql server 2005. i want data with comma. for example ['5000'],['5001'],..
but the last record should not include comma. Pls help me.
Query:
select '['''+convert(varchar,parcelid)+'''],' from sampletable
Try the COALESCE function
SELECT #groupedText = COALESCE(#groupedText, '') + [Text] + ','
FROM Requirement
WHERE CampaignId = #campaignId
ORDER BY [Text]
Then you could try one of the string functions to kill the end comma
T-SQL string functions
You can use regular expressions to remove the last comma or do it using your programming language (ASP etc. like a chop function or something).
http://weblogs.sqlteam.com/jeffs/archive/2007/04/27/SQL-2005-Regular-Expression-Replace.aspx
Consider using XML for this purpose. The "aggregate concatenation" solution may not be reliable, because it is not clearly documented and supported. You can get rid of the final comma with SUBSTRING, as boon suggested.
See this thread.