struggling with creating Insert query - sql

I create Insert statement for organization table like this:
select'Insert into Organizations(Name,ContactPerson,ContactNumber,Mobilenumber)values('''+Nameofthecompany+''+','+Nameofthepersonresponsibleforrecruitment+','+PhoneNumber+','+MobileNumber+''')' from Organization
When I execute this statement I get insert statement. But the issue is where the value is null, it shows all columns null.
Example: (in database)
Name: xxxx
ContactPerson: zzzz
ContactNumber:444444
MobileNumber: null
so my insert statement looks like:
Null.
I want only that column provide null. other details showing properly. Is there any way in sql server? Help me anyone...

The result of concatenating anything to NULL, even itself, is always NULL. Workaround with ISNULL function:
select'Insert into Organizations(Name,ContactPerson,ContactNumber,Mobilenumber)
values('''+ISNULL(Nameofthecompany, 'NULL')+''+','
+ISNULL(Nameofthepersonresponsibleforrecruitment, 'NULL')+','
+ISNULL(PhoneNumber, 'NULL')+','
+ISNULL(MobileNumber, 'NULL')+''')'
from Organization
Demo on SQLFiddle

Sure - just use ISNULL(..) to turn a NULL into e.g. an empty string:
SELECT
'INSERT INTO Organizations(Name, ContactPerson, ContactNumber, Mobilenumber) VALUES(''' +
ISNULL(Nameofthecompany, '') + '' + ',' +
ISNULL(Nameofthepersonresponsibleforrecruitment, '') + ',' +
ISNULL(PhoneNumber, '') + ',' + ISNULL(MobileNumber,'') + ''')'
FROM Organization

When you are adding each of the parameters to the SQL statement, you need to check whether they're null, and if so use the keyword NULL, otherwise include a literal string surrounded with single quotes, but bearing in mind that if the string contains any single quotes, they need to be replaced with two single quotes.
Update the SQL for each parameter something like the following:
CASE WHEN MobileNumber IS NULL THEN 'NULL' ELSE '''' + REPLACE(MobileNumber, '''', '''''') + '''' END

Related

How to add commas to a value?

Is it possible to add to the result value inside a column commas?
I mean for example I create new value:
insert into dbo.SAPID (TEST2)
Values (110)
I want the value to be with commas='110' inside the column result set.
insert into dbo.SAPID (TEST2)
Values (char(39) + '110' + char(39))
Please clarify your request. It seems like TEST2 is an Integer and you would like to return a string with single quotes surrounding it.
To do this you can cast the value when selected and append the quote:
SELECT '''' + CAST( TEST2 AS NVARCHAR(10) ) + '''' FROM SAPID
I believe you are thinking of single quotes '' like you provided in your example above:
I want the value to be with commas='110'
In that case, you could just do something like this:
--your column in the table will need to be a string instead of int
create table dbo.SAPID (TEST2 nvarchar(10));
--insert string value with single quotes
insert into dbo.SAPID(TEST2)
VALUES ('''' + '110' + '''');
--select statement
select * from dbo.SAPID
Single quote is an escape character in SQL much like other languages.Single quotes are escaped by doubling them up, just as shown in above example.
SQL Fiddle Demo

How to add '~' sign to a returned nvarchar value?

I am trying to add a '~' sign between two columns in SQL Server:
SELECT CODE + '~' + NAME FROM TEST_TABLE
It should return 'CCC~NNN' but it displays a newline instead of '~'. How can I fix this?
Maybe theres a hidden new line char in one of the selected fields. Try this:
SELECT REPLACE(REPLACE(CODE + '~' + NAME, CHAR(13), ''), CHAR(10), '') FROM TEST_TABLE
I would suggest using different column names in the future.
For now, it might suffice to simply surround your column names with brackets:
SELECT [CODE] + '~' + [NAME] FROM TEST_TABLE
Works fine for me.

How to default NULL to Zero

I'm creating sprocs with some calculations and I want to make sure I'm not missing something simple.
Say I'm finding a SUM() of a column that might have NULLs. Is there a single set statement that will convert NULL to Zero automatically without having to COALESCE each time? Or do I have to manually check for NULL each time?
I've looked through MSDN SET but I don't see anything useful.
There's a way to make NULL work with concatenation but I don't see anything for calculations.
For example:
SET ANSI_NULLS ON
SET CONCAT_NULL_YIELDS_NULL ON
--Calc
SELECT SUM(CONVERT(decimal(10,2), NULL))
SELECT SUM(CONVERT(decimal(10,2), Coalesce(NULL,0)))
--Concat
SELECT NULL + ', ' + 'Isaak' AS Name
SELECT COALESCE(NULL + ', ' + 'Isaak','') AS Name
SELECT COALESCE(NULL,'') + ', ' + 'Isaak' AS Name
--Change Concat NULL to OFF
SET ANSI_NULLS ON
SET CONCAT_NULL_YIELDS_NULL OFF
--Calc
SELECT SUM(CONVERT(decimal(10,2), NULL))
SELECT SUM(CONVERT(decimal(10,2), Coalesce(NULL,0)))
--Concat
SELECT NULL + ', ' + 'Isaak' AS Name
SELECT COALESCE(NULL + ', ' + 'Isaak','') AS Name
SELECT COALESCE(NULL,'') + ', ' + 'Isaak' AS Name
No, there is no magic way to do this. However there are multiple workarounds:
Stop allowing NULLs in the first place - add a default of 0 and if you can't update the DML logic then add a trigger (but far preferable to do this as part of the original insert/update).
Put the COALESCE into a view, and then reference the view in your queries.
Persist a zero (using COALESCE of course) into a separate, computed column, and change the calculation to use the computed column instead of the original column.

SQL Search Query With Null and ''

I have a query that I'm building for an application. The database is setup in SQL Server 2008. I want to use a query similar to below, however, I will be using this 'Where' clause for about 4 other columns using the same requirements. Is this the appropriate way to test for null or '' in a column that is VarChar(255) and does allow nulls.
Ideally, if the variable #UutSerialNumber is null or empty (''), I want all the results, but if it is not, I want to use the 'LIKE' clause. Is this the proper way of doing this and will it work? It seems to work until I start adding more columns to the Where clause.
Also, how would I handle a "text" datatype using the same type of query?
SELECT DeviceName, UutStatus
FROM MyTable
WHERE (UutSerialNumber LIKE '%' + #UutSerialNumber + '%' OR UutSerialNumber LIKE '%%' AND (#UutSerialNumber = '' OR #UutSerialNumber IS NULL)) AND ...
Help is appreciated. Thanks everyone!
It amy seem like duplication of SQL but the best way to do this is in terms of performace is using IF ... ELSE
IF ISNULL(#UutSerialNumber, '') = ''
BEGIN
SELECT DeviceName, UutStatus
FROM MyTable
-- MORE EXPRESSIONS
END
ELSE
BEGIN
SELECT DeviceName, UutStatus
FROM MyTable
WHERE (UutSerialNumber LIKE '%' + #UutSerialNumber + '%'
-- MORE EXPRESSIONS
END
It can be done within the WHERE clause if you are doing it on multiple columns and the query you posted wasn't far off it was just missing additional parenthesis along with having a redundant clause.
SELECT DeviceName, UutStatus
FROM MyTable
WHERE (ISNULL(#UutSerialNumber, '') = '' OR UutSerialNumber LIKE '%' + #UutSerialNumber + '%')
AND (ISNULL(#AnotherParameter, '') = '' OR AnotherColumn LIKE '%' + #AnotherParameter + '%')
Convert the text type to VARCHAR(MAX).
as a footnote, I personally would use the CHARINDEX rather than concatenating strings in the like:
WHERE (ISNULL(#UutSerialNumber, '') = '' OR CHARINDEX(#UutSerialNumber, UutSerialNumber) > 0)
This is nothing more than a footnote however as I have done no performance testing, I just think it is easier on the eye!
SELECT DeviceName, UutStatus
FROM MyTable
WHERE ((#UutSerialNumber = '') OR (#UutSerialNumber is null)) OR (UutSerialNumber like #UutSerialNumber)
add '%' to the last #UutSerialNumber if you think you need

LTRIM usage with SQL server 2005

I am a bit of an sql noob so please forgive. I can't seem to find a usage example of LTRIM anywhere.
I have a NVARCHAR column in my table in which a number of entries have leading whitespace - I'm presuming if I run this it should do the trick:
SELECT LTRIM( ColumnName)
From TableName;
Will this give the desired result?
No, it will trim leading spaces but not all white space (e.g. carriage returns).
Edit
It seems you are looking for an UPDATE query that will remove leading and trailing whitespace.
If by that you only mean "normal" spaces just use
UPDATE TableName
SET ColumnName = LTRIM(RTRIM(ColumnName ))
For all white space this should do it (from the comments here). Backup your data first!
UPDATE TableName
SET ColumnName =
SUBSTRING(
ColumnName,
PATINDEX('%[^ ' + char(09) + char(10) + char(13) + char(20) + ']%',
ColumnName),
LEN(ColumnName) - PATINDEX('%[^ ' + char(09) + char(10) + char(13) + char(20) + ']%'
, ColumnName) -
PATINDEX('%[^ ' + char(09) + char(10) + char(13) + char(20) + ']%',
REVERSE(ColumnName)) + 2)
Your example will work to remove the leading spaces. This will only select it from the database. IF you need to actually change the data in your table, you will need to write an UPDATE statement something like:
UPDATE TableName
SET ColumnName = LTRIM(ColumnName)
If you need to remove spaces from the right side, you can use RTRIM.
Here is a list of the string functions in SQL Server 2005 that I always refer to:
http://msdn.microsoft.com/en-us/library/ms181984(v=SQL.90).aspx
Did you run it to find out? It's just a select, it won't blow up your database. But, yes.
Select LTRIM(myColumn) myColumn
From myTable
Should return the myColumn values with any leading whitespace removed. Note this is only leading whitespace.
EDIT To Update the column, with the above, you'd do:
Update myTable
Set myColumn = LTRIM(myColumn)
From myTable