sql - using parameters in a in statement - sql

I am trying to run a simple script in SQL Server Management Studio.
Declare #total varchar (max)
set #total = 1
Declare #total2 varchar (max)
set #total2 = '1,4'
if #total in (#total2)
print 'Success'
For some reason I cannot get this simple script to work. It will work when I do this though "if 1 in ('1,2')" it will print "Success" Any help[ would be greatly appreciated.

You need to use Dynamic SQL because your #total contains varchar not numbers
Declare #total varchar (max)
set #total = 1
Declare #total2 varchar (max)
set #total2 = '1,4'
exec ('if '+#total+' in ('+#total2+') print ''Success'' ' )

IN works against sets, not strings. You could either declare a table variable and perform INSERT statements:
Declare #total varchar (max)
set #total = 1
Declare #total2 TABLE varchar (max)
(
total int
)
INSERT INTO #total2 VALUES (1)
INSERT INTO #total2 VALUES (4)
if #total in (SELECT total FROM #total2)
print 'Success'
or use string functions like CHARINDEX, but then you have to consider partial matches, etc.
You could convert a comma-delimited string to a table, but you'd still need to insert the values one-by one using a loop.

Related

Conversion of number not match with length of datatype in SQL Server

I refer the following number with datatype bigInt.
DECLARE #Number Bigint = '269687584'
When I convert the datatype to Varbinary(4), it returns 0x10131B20.
But when I calculate the length of the Varbinary data, it returns only 3.
I didn't know exact what wrong.
In SQL Server database, I want to write an query to convert Bigint to
Varbinary(4), but is converted as only as Varbinary(3).
Here is what I have tried:
DECLARE #Number BIGINT = '269687584'
SELECT
#Number,
CONVERT(VARBINARY(4), #Number),
LEN(CONVERT(VARBINARY(4), #Number))
Use DATALENGTH instead:
DECLARE #Number BIGINT ='269687584'
SELECT #Number, CONVERT(VARBINARY(4), #Number), DATALENGTH(CONVERT(VARBINARY(4), #Number))
There is nothing wrong. You should check lenght using datalength:
DECLARE #Number Bigint ='269687584'
SELECT #Number, CAST(#Number AS Varbinary(4)), DATALENGTH(CAST(#Number AS Varbinary(4)))

Extracting just hour and min from utcTimeStamp row from SQL table

So I have a situation where I know the procedure will query out a row that is formatted in UTCStampTime fashion. THe problem I am running into is when I want to build a query on the two CTE's I have need to be returned only when the time is equal on each CTE variables. But the problem is that my query only is looking at the last 10 minutes and I only want the two rows to be equal when the minutes of the utcTimeStamp columns are the same. here is my query that i am running.
GO
declare #fqnLine1Downtime varChar(4000)
declare #fqnLine1Throughput varChar(400)
declare #fqnLine2Downtime varChar(4000)
declare #fqnLine2Throughput varChar(400)
declare #parameter1Line1 varChar(4000)
declare #parameter2Line1 varChar(4000)
declare #parameter1Line2 varChar(4000)
declare #parameter2Line2 varChar(4000)
declare #server varChar(200)
declare #timeStart datetime
declare #timeEnd datetime
WITH
CTEThroughputLine1(Time, Amount, ThroughputLine1)
AS
--Define the query
(
SELECT CONVERT(VarChar(20),utcTimeStamp) as Time, shortName as
ThroughputLine1, valueAsInt as Amount
From dbo.History(#fqnLine1Throughput, #parameter2Line1, #timeStart,
#timeEnd, #server)
),
CTEThroughputLine2(ThroughputLine2, Amount, Time)
AS
(
Select shortName as ThroughputLine2, valueAsFloat as Amount,
CONVERT(VarChar(20),utcTimeStamp) as Time
From dbo.History(#fqnLine2Throughput, #parameter2Line2, #timeStart,
#timeEnd, #server)
)
select * from CTEThroughputLine1 as Line1 inner join
CTEThroughputLine2 as Line2 on Line1.Time = Line2.Time
I have purposefully not include the setting of the variables because it includes private info on my Company. I think this should be enough to tackle the problem. Please help or point out hints.

Why do I have two different return values from the queries in T-SQL

Hello I wonder why I have 2 different return Values.
Here is the first query:
declare #currentcolumn_val varchar
declare #start integer
set #currentcolumn_val = 'state_val'
set #start =1
select #currentcolumn_val from z_skm where id = #start
the returned value is just "s"
Here is the second Query which gives the correct return value:
select state_val from z_skm where id = 1
This query gives me exactly what it should.
I hope you guys can help.
Cheers steven
Your first query is returning a constant. The second is returning the value of the column.
You are returning 's' instead of 'state_val' because of the declaration:
declare #currentcolumn_val varchar;
You have no length on varchar() and in this context, it defaults to a length of 1. Always use length with varchar() in SQL Server.
If you want the column to be dynamic, you need to use dynamic SQL:
declare #currentcolumn_val nvarchar(255);
declare #start integer;
declare #sql nvarchar(max) = 'select #currentcolumn_val from z_skm where id = #start';
set #sql = replace(#sql, '#currentcolumn_val', #currentcolumn_val);
exec sp_executesql #sql, N'#start int', #start = #start;
You can pass a parameter as an argument, but not a column or table name.
You have declared #currentcolumn_val simply as varchar, which defaults to a length of 1.
if you replace it with declare #currentcolumn_val varchar(10) you will see the whole value
First you haven't given the #currentcolumn_val parameter a size so it is equivalent to a VARCHAR(1). This means that this:
set #currentcolumn_val = 'state_val'
Is the essentially the same as:
set #currentcolumn_val = 's'
Then in your SELECT you are returning the value of that variable, not a column from the table.

stored procedure returns nothing

This stored procedure doesn't work. It just returns 0 rows. I've checked the SQL and it returns the correct value when parsed directly to the DB. What could be wrong?
ALTER PROCEDURE dbo.GetSaltOfUser
(
#eMail nvarchar
)
AS
DECLARE #result nvarchar
/* SET NOCOUNT ON */
BEGIN
SELECT #result = salt
FROM UserSet
WHERE eMail = #eMail
RETURN #result
END
#eMail nvarchar
Will truncate the passed in email to one character. You need to put in a length. e.g.
#eMail nvarchar(50)
This should match the datatype of the relevant column in UserSet
Also do you really want to be using the return code for this or do you want to use an output parameter perhaps - or just a scalar select?
ALTER PROCEDURE dbo.GetSaltOfUser
(
#eMail nvarchar (50), /*Should match datatype of UserSet.eMail*/
#salt nvarchar (50) OUTPUT /*Should match datatype of UserSet.salt*/
)
AS
BEGIN
SET NOCOUNT ON
SELECT #result = salt
FROM UserSet
WHERE eMail = #eMail
END
And to call it
DECLARE #salt nvarchar(50)
EXECUTE dbo.GetSaltOfUser N'abc#example.com', #salt OUTPUT
SELECT #salt
You do not need to assign the salt to a variable.
CREATE PROCEDURE dbo.GetSaltOfUser
(
#eMail nvarchar
)
AS
BEGIN
SELECT salt
FROM UserSet
WHERE eMail = #eMail
END
Two Cents from my end
Good you are using SET NOCOUNT ON
Always use RETURN to return status code, Example 0- success, 1 - failure
Use SELECT to return the ROWS
Use Try Catch to handle Error Conditions

How to user prefix 'N' for unicode with nvarchar variable in SQL Server?

How to user prefix 'N' for unicode with nvarchar variable in SQL Server? For example:
Given this variable:
declare #Query1 nvarchar(max)
I can assign to it like this:
set #Query1 = N'لاحظات'
But what if I want to use N#Query1 somewhere?
You only need to use N'xyz' when you have literal text. Once the nvarchar data is in a variable or result set column of nvarchar data type you no longer need to use the N'...' notation, the system knows the data type at that point.
try it out:
DECLARE #A nvarchar(100)
,#B nvarchar(100)
SET #A = N'anything here!!'
SET #B=#A --would work the same if coming from a query result set as well
SELECT #B --will show special unicode characters
declare #nv1 nvarchar(50) = N'لاحظات', #nv2 nvarchar(50) = 'لاحظات', #v varchar(50) = N'لاحظات'
declare #nv3 nvarchar(50) = #nv1 + ' hallo', #nv4 nvarchar(50) = #nv1 + N' hallo'
select #nv1, #nv2, #nv3, #nv4, #v
It is used with string literals to indicate the text should be treated as unicode. e.g.
DECLARE #something NVARCHAR(100)
SET #something = N'sometext'
Declare #var nvarchar(255)
Set #var = N'Hello World'
print #var
create table #tmp( columnA nvarchar(255) not null)
insert into #tmp(columnA) Values (N'Test')
Select #var = columnA from #tmp
print #var
drop table #tmp
Thanks to marc_s for his answer, that solved my problem.
I highlight it here as an answer for those who can't find it.
"
if #Query1 IS a NVARCHAR variable, then it IS a NVARCHAR variable and you don't need to prefix it with another 'N' to make it NVARCHAR.... just use it
"