Concat NULL with Varchar SQL Server 2008 - sql-server-2008

I would like to ask how can I concatenate a nvarchar column with NULL without getting NULL? I would like to create an INSERT script using SELECT, but when any of the values is NULL, I get only NULL.
SELECT TOP 10
'IF NOT EXISTS(SELECT 1 FROM tblParameterKey
WHERE keyNames='''
+ CAST(ISNULL([keyNames], 'NULL') AS NVARCHAR(255)) + ''')
BEGIN
INSERT INTO tblParameterKey VALUES(''' + CAST(ISNULL([keyNames], 'NULL') AS NVARCHAR(255))+''')
END'
FROM tblParameterKey
This query returns correct insert inly when value is not null. If value is null it returns insert with 'NULL' which is not correct because it will be inserted as varchar and not as null value. If I remove ' ' the whole result will become null.

Edit - Maybe put the NULLIF statement inside the query string that way it will be null instead of string null.
SELECT TOP 10
'IF NOT EXISTS(SELECT 1 FROM tblParameterKey
WHERE keyNames=NULLIF('''
+ [keyNames] + ''', 'NULL') AS NVARCHAR(255))
BEGIN
INSERT INTO tblParameterKey VALUES(NULLIF(''' + [keyNames]+''', 'NULL') AS NVARCHAR(255))
END'
FROM tblParameterKey

Related

Mysql Using a variable within a case statement

Trying to do something very simple.
Want to Run a SP that checks if one of the arguments is null. If so, store an empty string in a log table, otherwise store the value.
CREATE DEFINER=`root`#`localhost` PROCEDURE `SP_TestVariable`(
Code1 varchar(255) ,
CodeToTest varchar(255)
)
BEGIN
CASE
WHEN CodeToTest IS NULL THEN
set #FinalCode = ' '
ELSE
set #FinalCode = CodeToTest
end
-- Now do the insert into the log table
INSERT INTO `TempLogTable` ( strField1, strField2)
VALUES (Code1 , #FinalCode );
You can reduce all that to a simle query
INSERT INTO `TempLogTable` (strField1, strField2)
SELECT Code1, coalesce(CodeToTest, '')
and for that I would even drop the procedure and just use the query instead.

MySQL Unknown column in 'order clause'

I have one procedure in my MySQL Database.
My procedure working fine. But currently I have to set order by tblUserKeyStatus.createdDate inside IF (opt=1) condition and when I set order by, It gives me the following error
Error Code: 1054. Unknown column 'tblUserKeyStatus.createdDate' in 'order clause
My Stored Procedure is given below
CREATE PROCEDURE proc_GetStatus(IN _userId varchar(64) , IN _qtr int, IN opt int)
BEGIN
IF (opt = 1) then
SELECT tblKeyStatus.*,'pending' AS `Status`,'' as scheduleDate,
' ' as doneDate,' ' as result FROM tblUserKeyStatus,tblKeyStatus WHERE tblKeyStatus.trimId not in
(SELECT trimId from tblUserKeyStatus WHERE userId=_userId)
union
SELECT tblKeyStatus.*,tblUserKeyStatus.`Status` AS `Status`,tblUserKeyStatus.scheduleDate,
tblUserKeyStatus.doneDate,tblUserKeyStatus.result FROM tblKeyStatus,tblUserKeyStatus WHERE
tblUserKeyStatus.trimId=tblKeyStatus.trimId and tblUserKeyStatus.userId=_userId
order by tblUserKeyStatus.createdDate;
Else
SELECT * from tblKeyStatus WHERE qtr=_qtr;
End if;
END
ORDER BY is applied to the whole query specified in the UNION operation, so that the entire result set returned by UNION is ordered.
Try to select createdDate field in both subqueries, so that it is accessible to ORDER BY:
SELECT tblUserKeyStatus.createdDate,
tblKeyStatus.*,'pending' AS `Status`,
'' as scheduleDate,
' ' as doneDate,
' ' as result
FROM tblUserKeyStatus, tblKeyStatus
WHERE tblKeyStatus.trimId not in (SELECT trimId
from tblUserKeyStatus
WHERE userId=_userId)
UNION
SELECT tblUserKeyStatus.createdDate,
tblKeyStatus.*,
tblUserKeyStatus.`Status` AS `Status`,
tblUserKeyStatus.scheduleDate,
tblUserKeyStatus.doneDate,tblUserKeyStatus.result
FROM tblKeyStatus,tblUserKeyStatus
WHERE tblUserKeyStatus.trimId=tblKeyStatus.trimId and
tblUserKeyStatus.userId=_userId
ORDER BY createdDate;
You also have to remove the tblUserKeyStatus name prefix.
Try having braces for select
CREATE PROCEDURE proc_GetStatus(IN _userId varchar(64) , IN _qtr int, IN opt int)
BEGIN
IF (opt = 1) then
SELECT tblKeyStatus.*,'pending' AS `Status`,'' as scheduleDate,
' ' as doneDate,' ' as result FROM tblUserKeyStatus,tblKeyStatus WHERE tblKeyStatus.trimId not in
((SELECT trimId from tblUserKeyStatus WHERE userId=_userId)
union
(SELECT tblKeyStatus.*,tblUserKeyStatus.`Status` AS `Status`,tblUserKeyStatus.scheduleDate,
tblUserKeyStatus.doneDate,tblUserKeyStatus.result FROM tblKeyStatus,tblUserKeyStatus WHERE
tblUserKeyStatus.trimId=tblKeyStatus.trimId and tblUserKeyStatus.userId=_userId
order by createdDate));
Else
SELECT * from tblKeyStatus WHERE qtr=_qtr;
End if;
END

Quick Help on stored procedure .adding headers to output

How can I modify this stored procedure to output the headers in the export? It works with the bcp utility when assigned to a SQL Server Agent but I need to have the file also export out the headers in the file (as well as the contents of the select)
CREATE PROCEDURE [dbo].[GL_Export]
AS
DECLARE #gl table
(AccCode VARCHAR(3000),
CodeDesc VARCHAR(3000),
AccountType_id VARCHAR(3000),
AccGroupName VARCHAR(3000)
)
-- Inserts data into #temptable (memory)
INSERT #gl
SELECT DISTINCT
RTRIM (s1.SGMNTID) AS 'AccCode',RTRIM (s1.DSCRIPTN) AS 'CodeDesc',
CASE
WHEN s1.SGMTNUMB = '1' THEN '1'
WHEN s1.SGMTNUMB = '2' THEN '2'
WHEN s1.SGMTNUMB = '3' THEN '110'
WHEN s1.SGMTNUMB = '4' THEN '4'
WHEN s1.SGMTNUMB = '5' THEN '120'
END AS 'AccountType_id',
CASE
WHEN s1.SGMTNUMB = '2' THEN LEFT(s1.SGMNTID, 2)
ELSE 'DEFAULT'
END AS 'AccGroupName'
FROM
GL40200 s1
UNION
SELECT
REPLACE ([ACTNUMBR_1] + '-' + [ACTNUMBR_2] + '-'
+ [ACTNUMBR_3] + '-' +[ACTNUMBR_4] + '-'
+ [ACTNUMBR_5], ' ', '') AS 'AccCode',
'' AS 'CodeDesc',
'0' AS 'AccountType_id',
'Default' AS 'AccGroupName'
FROM
GL00100 a
-- Selects the output for memory and should add headers to file
SELECT
AccCode, CodeDesc, AccountType_id, AccGroupName
FROM #gl
UNION
Select AccCode,CodeDesc,AccountType_id,AccGroupName from #gl
GO
You could use UNION ALL and have one SELECT that has the column headings, and then another with the actual values cast to varchar as appropriate:
SELECT 'AccCode', 'CodeDesc', 'AccountType_id', 'AccGroupName'
UNION ALL
SELECT
CAST(AccCode AS varchar(100)),
CAST(CodeDesc AS varchar(100)),
CAST(AccountType_id AS varchar(100)),
CAST(AccGroupName AS varchar(100))
FROM #gl
(Of course, if some columns are already non-numeric you could leave them as such, otherwise CAST as appropriate.)

Creating a dynamic where clause in SQL Server stored procedure

I am trying to create a stored that will accept two values, a column name and a value. It will then check if there is a record that exists for the passed in column name with the passed in value. I've tried the following
CREATE PROCEDURE p_HasActiveReference
#pi_colName varchar(100)
,#pi_colValue varchar(100)
AS
BEGIN
SET NOCOUNT ON
declare #sql varchar(1000)
set #sql = 'IF EXISTS(SELECT TOP 1 p.PaymentId
FROM Payments p
WHERE ' + #pi_colName + ' = ' + #pi_colValue + 'AND Active = 1)
SELECT ''True'' AS RETVAL
ELSE
SELECT ''False'' AS RETVAL'
exec(#sql)
END
However, I always get this error
Conversion failed when converting the varchar value 'InternalOr' to data type int.
When I call the procedure with the following
p_HasActiveReference 'InternalOrgCode', '10110'
The internalOrgCode column is of value varchar(10)
I am not a SQL expert, so I am not even sure if what I need to achieve is even possible using that technique!
Thanks!
At least one issue: you should be surrounding your string value with single quotes, and to escape those inside a string you need to double them up:
WHERE ' + #pi_colName + ' = ''' + #pi_colValue + ''' AND ...
You also may want to declare your #sql variable as something bigger than 100 characters! Looks like your string is getting truncated.
If the possible values for #pi_colName are finite, the data type is always string, and the columns are collation compatible, you could do something like this and avoid dynamic SQL:
SELECT ...
WHERE CASE #pi_colName
WHEN 'col1' THEN col1
WHEN 'col2' THEN col2
END = #pi_ColValue;

In MySQL stored procedures check if a local variable is null

With the following example stored procedure
DECLARE Variable DOUBLE;
DECLARE Variable2 DOUBLE;
SELECT Something FROM Somewhere INTO Variable;
SELECT Something FROM SomewhereElse INTO Variable 2;
SELECT (Variable + Variable2);
If either Variable or Variable2 are NULL then the final SELECT will return null, what I would like is that if they are null they should be converted into 0.00 before the final SELECT, how do you do this? I already tried adding
SELECT 0.00 INTO Variable WHERE Variable IS NULL;
just above the final select but that didn't work.
SELECT COALESCE(variable, 0) + COALESCE(variable2, 0)
if you want each variable null converted to 0 use the solution posted by Quassnoi
SELECT COALESCE(variable, 0) + COALESCE(variable2, 0)
if you want to have 0 if either variable is null then use
SELECT COALESCE(variable + variable2, 0)
Quassnoi's correct, but it's even simpler (and a bit faster) to just coalesce the result:
SELECT coalesce( Variable + Variable2, 0 );
This works because for almost all operators, any null operand will make the operation null:
select 1 + null ; -- null
select null + 1 ; -- null
select null + null ; -- null
In the expression: SELECT coalesce( Variable + Variable2, 0 ); the result of the addition expression Variable + Variable2 is coalesce first argument; if that's null, coalesce returns its second argument, 0, otherwise it returns the (non-null) value of its first argument, which is the sum we want.
The few operators and functions that don't return null for a null operand are those designed to work on nulls: coalesce, is null, is not null.
As kristof notes below, the value of the select expression is different using Quassnoi's expression, if only one variable is null: his will return the value of the non-null variable if one is null; mine will return zero if either variable is null. Which is "right" depends on your intent.