How do I identify a blank uniqueidentifier in SQL Server 2005? - sql-server

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

Related

how to use declare variable in select query in stored procedure using sql server

Hello I want to concate two things one is string and other is int variable. Now, these thing I want to store in one variable and use that variable in select query as a into type to create a temptable in stored procedure using sql server.
Here is my query
USE [FlightExamSoftware]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- For Storing Question in Temp table
-- EXEC [GetQuestionListPerSubjectRatioWise] 1,11
ALTER PROCEDURE [dbo].[GetQuestionListPerSubjectRatioWise]
#SubjectID INT,
#NumberOfQue INT,
#UserID int
AS
BEGIN
DECLARE #strQuery VARCHAR(MAX);
DECLARE #PerChapQue INT;
DECLARE #tempTable VARCHAR(MAX) = 'tempTestUser' + #UserID;
SELECT #PerChapQue = COUNT(appQueID)/#NumberOfQue FROM tblQuestion WHERE appQueSubID=#SubjectID
SELECT COUNT(appQueID)/#PerChapQue ChapwiseQue
,CASE WHEN COUNT(appQueID)>=#PerChapQue THEN COUNT(appQueID)/#PerChapQue ELSE 1 END ChapWiseQuePlusOne
,appQueChapID into #tempTable
FROM tblQuestion
WHERE appQueSubID=#SubjectID
GROUP BY appQueChapID
END
Now, I am talking about these line
DECLARE #tempTable VARCHAR(MAX) = 'tempTestUser' + #UserID;
In these line two things are concate one is string and other is int. And store in varchar variable.
And use in following select query i.e.
SELECT COUNT(appQueID)/#PerChapQue ChapwiseQue
,CASE WHEN COUNT(appQueID)>=#PerChapQue THEN COUNT(appQueID)/#PerChapQue ELSE 1 END ChapWiseQuePlusOne
,appQueChapID into #tempTable
FROM tblQuestion
WHERE appQueSubID=#SubjectID
GROUP BY appQueChapID
END
Now, in these query I want to create a temptable named #tempTable.
But, in these line it showing error i.e. Incorrect syntax near '#tempTable'.
Confuse that where is the syntax is wrong.
Thank You.
There are a number of things wrong with your code.
When concatenating an int to a string, you must first cast the int to varchar. Otherwise, SQL Server will try to implicitly convert the string to int, that will result with an error.
So this: DECLARE #tempTable VARCHAR(MAX) = 'tempTestUser' + #UserID; should become this:
DECLARE #tempTable VARCHAR(MAX) = 'tempTestUser' + CAST(#UserID AS VARCHAR(11)); (you need 11 chars to be able to fit the minimum value of int: -2,147,483,648)
You can't use select...into with a table variable.
You can only use it for actual tables (temporary or regular).
your #tempTable isn't even a table variable (not that it will help with a select...into).
Even if you would use select...into the correct way, unless you are going to use a global temporary table (and that doesn't come without it's risks), Unless your stored procedure uses this temporary table later on, it will be useless, since temporary tables are bound to scope.
Taking all of that into consideration I'm not sure what output you are actually looking for. If you could edit your question to include the desired output of your stored procedure as well as some sample data as DDL+DML, it would be easier to help you write better code.
Hope this Dynamic Query helps you:
Try like this:
USE [FlightExamSoftware]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- For Storing Question in Temp table
-- EXEC [GetQuestionListPerSubjectRatioWise] 1,11
ALTER PROCEDURE [dbo].[GetQuestionListPerSubjectRatioWise]
#SubjectID INT,
#NumberOfQue INT,
#UserID int
AS
BEGIN
DECLARE #strQuery VARCHAR(MAX);
DECLARE #PerChapQue INT;
DECLARE #tempTable VARCHAR(MAX) = 'tempTestUser' + CAST(#UserID AS VARCHAR);
SELECT #PerChapQue = COUNT(appQueID)/#NumberOfQue FROM tblQuestion WHERE appQueSubID=#SubjectID
SET #strQuery='
SELECT COUNT(appQueID)/'+CAST(#PerChapQue AS VARCHAR)+' ChapwiseQue
,CASE WHEN COUNT(appQueID)>='+CAST(#PerChapQue AS VARCHAR)+' THEN COUNT(appQueID)/'+CAST(#PerChapQue AS VARCHAR)+' ELSE 1 END ChapWiseQuePlusOne
,appQueChapID
INTO '+#tempTable+'
FROM tblQuestion
WHERE appQueSubID='+CAST(#SubjectID AS VARCHAR)+'
GROUP BY appQueChapID
/*.................................
And you have to use the temp table inside the String only
.................................*/
'
EXEC (#strQuery)
END

Return length of NVARCHAR or VARCHAR variable definition

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!

How to add varchar and integer in sql server

I have to convert int to varchar and need to take care about one more consideration.
For example:
1)My string length is always 10 characters.
(i.e. "0000000001")
Whenever I generated a new id, it has to increment (i.e. "0000000002")
When it reaches the 10th string will be "0000000010", etc...
I have no idea how to implement this.
trying as a first step.
--Declared variable to increment count
declare #CTR INT
--#LIPRequestID is integer this is what i have to add to my
declare #LIPRequestID int
select #LIPRequestID=0
declare #LIPRequestIDstring varchar(max)
select #ctr=0
WHILE #CTR<2
BEGIN
select #ctr=#ctr+1
select #LIPRequestID=#LIPRequestID+1
select #LIPRequestIDstring='00000000'+ CAST(#LIPRequestID AS VARCHAR(10)
print #LIPRequestIDstring
END
but it is throwing the following exception error:
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near '#LIPRequestIDstring'.
can anybody suggest where I am going wrong?
Instead of concatenating the string literal 00000000 with the ID you should use RIGHT:
DECLARE #LIPRequestIDstring varchar(10);
DECLARE #nextLIPRequestID int;
SET #nextLIPRequestID = (SELECT MAX(LIPRequestID) FROM dbo.TableName) + 1;
SET #LIPRequestIDstring = RIGHT('0000000000'+ CONVERT(VARCHAR(10),#nextLIPRequestID),10)
Parenthesis missing in cast function, other things looks fine
select #LIPRequestIDstring='00000000'+ CAST(#LIPRequestID AS VARCHAR(10))--here
Instead of
CAST(#LIPRequestID AS VARCHAR(10)
use
CAST(#LIPRequestID AS VARCHAR(10))
Instead of RIGHT function, we can use REPLACE function. This will help you to implement your two requirements. The length of the ID also can be passed as parameter #IDLength.
DECLARE #CTR INT = 0
DECLARE #LIPRequestID INT = 0
DECLARE #IDLength INT = 8
DECLARE #LIPRequestIDstring VARCHAR(MAX)
WHILE (#CTR < 12)
BEGIN
SELECT #CTR += 1
SELECT #LIPRequestID += 1
PRINT REPLACE(STR(#LIPRequestID, #IDLength), SPACE(1), '0')
END
Yes, Right function really make sence, thanks to sql and stackoverflow.
declare #LIPRequestIDstring varchar(max)
select #LIPRequestID=#LIPRequestID+1
select #LIPRequestIDstring=RIGHT('0000000000'+ CONVERT(VARCHAR(10),#LIPRequestID),10)

SQL Server 2008: Finding a value from a string

This might be a very simple select statement, here's my question.
I have a variable
DECLARE #A varchar(128) --declaring variable
SET #A = 'sus_123456_R5_20140506' --setting value
I want to find the value after 'sus_' and before 'R5'
Also, the value in between is not of fixed length. So the function has to be dynamic.
However it always have sus and _R5_date. That's constant.
SET #A = 'sus_129_R5_20150408
Thanks
Use SUBSTRING in combination with CHARINDEX:
SELECT SUBSTRING(#A,CHARINDEX('sus_',#A,0)+4,CHARINDEX('_R5',#A,0)-5)
You can try this once using SUBSTRING() and CHARINDEX() FUNCTION
DECLARE #A varchar(128) --declaring variable
SET #A = 'sus_123456_R5_20140506'
select substring(#A,charindex('_',#A)+1,charindex('r5',#A)- (2+charindex('_',#A)))
Results in: 123456
(OR) This one using LEFT(),RIGHT() and CHARINDEX() function.
DECLARE #A varchar(128)
SET #A = 'sus_129_R5_20150408'
select right(left(#A,charindex('R5',#A) - 2),charindex('_',#A) - 1)
Results in: 129
Read more about String Function

Check for empty GUID in SQL

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'

Resources