How do I check if an argument in a stored procedure is an empty GUID or not?
SELECT CAST(CAST(0 AS BINARY) AS UNIQUEIDENTIFIER)
That should return your empty guid.
... or even shorter, saving one cast:
SELECT CAST(0x0 AS UNIQUEIDENTIFIER)
So to check for that, you would do
IF #GuidParam = CAST(CAST(0 AS BINARY) AS UNIQUEIDENTIFIER)
BEGIN
--Guid is empty
END
Since the empty guid never changes, the other obvious way is to simply use 00000000-0000-0000-0000-000000000000 rather than calculating it.
If #Param = '00000000-0000-0000-0000-000000000000'
...
Or, if in an procedure, you can set a parameter to act as a constant:
Declare #EmptyGuid uniqueidentifier
Set #EmptyGuid = '00000000-0000-0000-0000-000000000000'
Or you could create a scalar user-defined function which simply returns the above constant value (or recalculates it as in Meiscooldude solution).
DECLARE #EmptyGuid UNIQUEIDENTIFIER = 0x0
DECLARE #NonEmpty UNIQUEIDENTIFIER = NEWID()
IF #EmptyGuid = 0x0 PRINT 'Empty'
IF #NonEmpty = 0x0 PRINT 'Empty' ELSE PRINT 'NonEmpty'
Will print
Empty
NonEmpty
You can make Empty Guid like this:
DECLARE #EmptyGuid UNIQUEIDENTIFIER
SET #EmptyGuid = (SELECT CAST(CAST(0 AS BINARY) AS UNIQUEIDENTIFIER))
-- Single result is 00000000-0000-0000-0000-000000000000
SELECT #EmptyGuid
Use
DECLARE #param UNIQUEIDENTIFIER = NEWID();
--DECLARE #param UNIQUEIDENTIFIER = '00000000-0000-0000-0000-000000000000'
IF (CONVERT(UNIQUEIDENTIFIER, 0x00)) = #param
PRINT 'Empty';
ELSE
PRINT 'Not Empty';
DECLARE #SupplierDataHubId uniqueidentifier=null
set #SupplierDataHubId=(select HubId from dbo.tblSupplierData where fldUpc='603259049389' OR fldEan='6032590493895555')
if (#SupplierDataHubId is not null)
begin
print('yes');
end
else
print 'no'
Related
I am not expert in functions. Inherited the following function which is very slow
ALTER FUNCTION [dbo].[fn_Diagnosed]
( #clientId As int)
RETURNS NVARCHAR(10)
AS
BEGIN
DECLARE #result int;
Declare #return nvarchar(10);
set #result = (SELECT COUNT(*)
FROM dbo.AdditionalInfo
WHERE dbo.AdditionalInfo.Type = 'Diagnosed' and ClientId = #ClientId);
IF #result > 0
set #return = 'Yes'
ELSE
set #return = 'No';
return #return;
END
Is this the right way to write a function?
Your function looks fine. An index is not automatically created on a foreign key constraint. So, you should explicitly add an index, like this
CREATE INDEX ClientAdditionalInfo_ClientID
ON [dbo].[ClientAdditionalInfo]
(ClientID)
INCLUDE ([Type])
I've declared a variable in a stored procedure:
DECLARE #CurrentChunk NVARCHAR(250)
I would like to use the length of the variable, i.e. 250, later in my sp for computational purposes, and I want to keep my code as dry as possible.
Here's my code (assume #Narrative is a param to the SP):
DECLARE #ChunkSizeCharacters INT,
#NumChunks INT,
#LoopIndex INT,
#CurrentChunk NVARCHAR(250)
SET #ChunkSizeCharacters = 250 -- HERE'S WHERE I WANT THE LENGTH OF #CurrentChunk
SET #NumChunks = CEILING((LEN(#Narrative) * 1.0)/#ChunkSizeCharacters)
SET #LoopIndex = 0;
WHILE (#LoopIndex < #NumChunks)
BEGIN
SET #CurrentChunk = SUBSTRING(#Narrative,
((#LoopIndex * #ChunkSizeCharacters) + 1), #ChunkSizeCharacters)
INSERT INTO [dbo].[Chunks] ([Chunk]) VALUES (#CurrentChunk)
SET #LoopIndex = #LoopIndex + 1
END
Is there a way to ascertain the length of an NVARCHAR or VARCHAR variable definition (please read carefully -- I'm not looking for LEN())?
It seems the MaxLength variant property returns the value you're looking for.
DECLARE #Banana varchar(255) = 'This banana'
SELECT SQL_VARIANT_PROPERTY(#Banana, 'MaxLength')
Returns 255.
If you don't mind overwriting the variable (and if you do, you can assign it to a temp NVARCHAR(MAX)):
SELECT #CurrentChunk = REPLICATE(0, 8000);
SELECT #ChunkSizeCharacters = LEN(#CurrentChunk);
This trick does not and cannot work for NVARCHAR(MAX), but that's presumably no problem, given it's enormous maximum size.
Unfortunately T-SQL has nothing in the way of metadata properties for variables. Even determining the type of an expression is a chore.
Interestingly, the value returned by that SELECT SQL_VARIANT_PROPERTY statement doesn't select into a plain, predefined variable. In the end, I used:
DECLARE #Text VARCHAR(400), #TextLen INT
SELECT #TextLen = CAST(SQL_VARIANT_PROPERTY(ISNULL(#Text, ''), 'MaxLength') AS INT)
Works like a charm for me!
When I have a query such as :
SELECT top 1 LabResult_Result as Value
FROM [TopsData].[dbo].[VIEW_PatientLabResult]
where MasterLabCode_ID = '000000003H'
and Patient_ID = 'ZZZZZ00063'
and LabResult_RecordState = 0
and datediff(d,'11/19/2013',LabResult_DateTimeOfObservation) >= 0
ORDER BY LabResult_DateTimeOfObservation
the result is nice, usually a varchar that resembles a decimale such as 1.10
However, if I wrap this in a function, it returns just a 1:
declare #R varchar(10)
SELECT #R = Value FROM (
SELECT top 1 LabResult_Result as Value
FROM [TopsData].[dbo].[VIEW_PatientLabResult]
where MasterLabCode_ID = '000000003H'
and Patient_ID = 'ZZZZZ00063'
and LabResult_RecordState = 0
and datediff(d,'11/19/2013',LabResult_DateTimeOfObservation) >= 0
ORDER BY LabResult_DateTimeOfObservation
)q
return #R
END
Obviously I have plans to make it generic with parameters,etc.. But if the hardcoded query wont return the correct varchar, I do not know what to do.
I bet your functions says:
RETURNS VARCHAR
Or:
#input VARCHAR
Instead of:
RETURNS VARCHAR(10)
Or:
#input VARCHAR(10)
Full repro... both of these function calls return a:
USE tempdb;
GO
CREATE FUNCTION dbo.foo1
(
#a VARCHAR(10)
)
RETURNS VARCHAR
----- LAZY! ---^^^^ Missing length specification!
AS
BEGIN
RETURN #a;
END
GO
SELECT dbo.foo1('abcdefghij');
GO
CREATE FUNCTION dbo.foo2
(
#a VARCHAR
---- LAZY! ^^^^ Missing length specification
)
RETURNS VARCHAR(10)
AS
BEGIN
RETURN #a;
END
GO
SELECT dbo.foo2('abcdefghij');
GO
DROP FUNCTION dbo.foo1, dbo.foo2;
GO
Always, always, always specify a length when declaring or defining variable-width types in any context. In some cases SQL Server will assume you meant 1, in some cases 30, in very few cases is either guess correct. More info here:
Bad habits to kick : declaring VARCHAR without (length)
I'm getting a uniqueidentifier into a Stored Procedure that looks like this
00000000-0000-0000-0000-000000000000.
This seems like a simple thing, but how can identify that this is a blank uniqueidentifier?
If I get a value like this DDB72E0C-FC43-4C34-A924-741445153021 I want to do X
If I get a value like this 00000000-0000-0000-0000-000000000000 I do Y
Is there a more elegant way then counting up the zeros?
Thanks in advance
compare to
cast(cast(0 as binary) as uniqueidentifier)
?
Just create an EmptyGuid variable and compare against that:
DECLARE #EmptyGuid UniqueIdentifier
SET #EmptyGuid = '00000000-0000-0000-0000-000000000000'
IF (#TheGuid = '00000000-0000-0000-0000-000000000000')
SELECT 'Do Y'
ELSE
SELECT 'Do X'
This also works.
DECLARE #EmptyGuid UNIQUEIDENTIFIER = CONVERT(UNIQUEIDENTIFIER, 0x0);
SELECT #EmptyGuid
Best solution is to use a constant for the empty GUID
DECLARE #EmptyGuid UNIQUEIDENTIFIER
SET #EmptyGuid = '00000000-0000-0000-0000-000000000000'
OR
DECLARE #EmptyGuid UNIQUEIDENTIFIER
SET #EmptyGuid = 0x0
and you just compare them
IF #parameter = #EmptyGuid
DO Y
ELSE
DO X
Note: you don't need to use casts and converts
I would like to know if in SQL is it possible to return a varchar value from a stored procedure, most of the examples I have seen the return value is an int.
Example within a procedure:
declare #ErrorMessage varchar(255)
if #TestFlag = 0
set #ErrorMessage = 'Test'
return #ErrorMessage
You can use out parameter or the resulset to return any data type.
Return values should always be integer
CREATE PROCEDURE GetImmediateManager
#employeeID INT,
#managerName VARCHAR OUTPUT
AS
BEGIN
SELECT #managerName = ManagerName
FROM HumanResources.Employee
WHERE EmployeeID = #employeeID
END
Taken from here
You will need to create a stored function for that:
create function dbo.GetLookupValue(#value INT)
returns varchar(100)
as begin
declare #result varchar(100)
select
#result = somefield
from
yourtable
where
ID = #value;
return #result
end
You can then use this stored function like this:
select dbo.GetLookupValue(4)
Marc
A stored procedure's return code is always integer, but you can have OUTPUT parameters that are any desired type -- see http://msdn.microsoft.com/en-us/library/aa174792.aspx .