assigning results of sql query to local variables - sql

Result of a SQL query can be assigned to a local variable like this:
declare #name varchar(30)
select #name = (select name from dummyTable where id = 10)
But what if I have to assign multiple column values to multiple local variables?
Say I have #address, #serialNumber, #grade, #phoneNumber.
Do I have to perform multiple select statements? Like this
select #address = (select address from dummyTable where id = 10)
select #serialNumber = (select serialNumber from dummyTable where id = 10)
....
Is there a way I can do this assignment in 1 select statement?
Thanks

Try this below
select #address = address ,
#serialNumber = serialNumber
from dummyTable where id = 10

Related

Filter via different dates in where clause

Here I've created a simple table using MS SQL
CREATE TABLE Students1 (
FirstName Nvarchar(100),
SecondName Nvarchar(100),
DOB Smalldatetime,
RegisterDate smalldatetime,
Archived int,
ArchivedDate Smalldatetime
);
Insert Into Students1(FirstName,SecondNAme,DOB,RegisterDate,Archived,ArchivedDate)
Values('James','Bike',16/04/1900, 04/07/2017,0,Null);
Insert Into Students1(FirstName,SecondNAme,DOB,RegisterDate,Archived,ArchivedDate)
Values('Adam','Bike',16/04/1901,04/07/2017,0,Null);
Insert Into Students1(FirstName,SecondNAme,DOB,RegisterDate,Archived,ArchivedDate)
Values('Chris','Bike',16/04/1902,04/09/2017,1,getdate());
Insert Into Students1(FirstName,SecondNAme,DOB,RegisterDate,Archived,ArchivedDate)
Values('Sam','Bike',16/04/1999,04/09/2017,1,getdate());
Insert Into Students1(FirstName,SecondNAme,DOB,RegisterDate,Archived,ArchivedDate)
Values('Josh','Bike',16/04/1999,04/09/2017,1,getdate());
I want to do a simple select statement against this where I'm filtering on the either the RegisterDate or the ArchivedDate depending on how my local variables are set up.
For instance, i will have the following local variables set;
#FitlerRegisterDate
#FilterArchived
If either #FilterREgisterDate is set to 1 then the where clause will look at the RegisterDate column, but if the #FilterArchived is set to 1 then the where clause will look at the ArchivedColumn AND if they're both set to 1 then it should default to look at the RegisterDate
I've had a look at this for a while and cant see anything that stands out. If someone could point me in the right direction, that would be great.
Thanks.
You can use AND and OR clause to filter according to your variable values:
SELECT *
FROM dbo.Students1
WHERE ( #FilterArchived = 1
AND #FilterREgisterDate = 1
AND RegisterDate = #dateToFilter )
OR ( ( #FilterREgisterDate = 1
AND RegisterDate = #dateToFilter )
OR ( #FilterArchived = 1
AND ArchivedDate = #dateToFilter ) )
Something like this :
SELECT *
FROM Students1
WHERE #FilterREgisterDate = 1 AND RegisterDate = #RegisterDate
OR #FilterREgisterDate <> 1 AND #FilterArchived = 1 AND ArchivedDate = #ArchivedDate
;
?
select * from dbo.Students1 where (#FilterArchived=1 AND #FilterREgisterDate=1) and registerdate='04/07/2017'
UNION
select * from dbo.Students1 where (#FilterArchived!=1 AND #FilterREgisterDate=1) and registerdate='04/07/2017'
UNION
select * from dbo.Students1 where (#FilterArchived=1 AND #FilterREgisterDate!=1) and archived=1

Using ORDER BY command in an UPDATE SQL

I am looking at updating an item number column from a number of rows in a table (which match a particular Product ID & type) but I want to order the rows by numbers in a 'Seqnumber' column then the item number column start at 1 and count each row sequentially by 1.
Using the code below I have been able to select the product id and type I want and update the item number column with sequentially increasing values, however I don't know how I can order the required rows?
DECLARE #id nvarchar(6)
SET #id = 0
UPDATE Table1
SET #id = Table1.ItemNumber = #id + 1
WHERE Product = '5486' AND Table1.Type = 'C'
I know you can't use the ORDER BY command within the UPDATE command without using it as a sub-query. But I'm not sure how I should include this in the above code?
I think I need to incorporate the code below but not sure what the SELECT statement should be and when I try I can't get it to work?
DECALRE #id nvarchar(6)
SET #id = 0
UPDATE Table1
SET #id = TABLE1.ItemNumber = #id + 1
FROM (SELECT TOP (??)* FROM Table1
WHERE Product = '5486' AND Table1.Type ='C'
ORDER BY Table1.SeqNumber ASC
You should be able to build a CTE with the values you want from the table and just update the CTE
declare #Table1 table (Product varchar(4), [Type] varchar(1), SeqNumber int, ItemNumber int)
INSERT INTO #Table1 VALUES
('5486', 'C', 3, 0),
('5486', 'C', 2, 0);
with cte as (
select *,
ROW_NUMBER() OVER (ORDER BY SeqNumber) rn
from #Table1
where Product = '5486' and Type ='C'
)
Update cte
set ItemNumber = rn
This should work:
SET #id = 0;
UPDATE Table1
SET #id = Table1.ItemNumber = (#id := #id + 1)
WHERE Product = 5486 and Table1.Type = 'C'
ORDER BY Table1.seqnumber;
You cannot use ORDER BY with a JOIN, so you need to initialize the variable before the update.
UPDATE sales_data
SET ID = ID + 1
ORDER BY ID DESC;

How can I assign value into difference parameter from the same time in SQL Server?

How can I assign value into difference parameter from the same time in SQL Server?
Example:
I have table that has columns age, name, address. How can I assign those values into the declared parameters #age int, #name varchar(max) and #address varchar(max)?
I wrote the following code, but it's not working
set #age = age,
set #name = name,
set #address = address
from [dbo].[test]
I don't know which DMBS you are using, but in mysql you can do this:
select #name := name, #age := age from dbo.test
Of course it will only store the field of the last row matched, so you will need to use an appropriate where clause to choose the row you are interested in.
You can also use the set command, but you will need a separate query for each field you want set:
set #name = (select name from dbo.test limit 1)
set #age = (select age from dbo.test limit 1)
SELECT #age = age,#name = name,#address = address FROM [dbo].[test]
SELECT #age = age,
#name = name,
#address = address
FROM dbo.test
WHERE primarykey = somevalue

IF ELSE condition in SQL select

I want to do a if-else condition statement in SQL Server but am not sure how.
Inside the stored procedure I have the following parameters:
#MarketId nvarchar (10),
#RegionId nvarchar (10)
And the following statement:
select * from Interaction I
where
(#MarketId = 0 ) OR (I.MarketId = (SELECT Id FROM Market WHERE ExternalId = #MarketId))
What I want to do is to check the value of #MarketId
if #MarketId = 0
then I want the where condition for I.MarketId to get its Ids from elsewhere like
(SELECT ID FROM Market WHERE ExternalId = #RegionId)
otherwise, if its 1, then I just want to leave it as is and get the Id from #MarketId instead of #RegionId..
How should I go about this?
Thanks!
This should work:
SELECT *
FROM Interaction I
WHERE ( #MarketID = 0
AND EXISTS (SELECT 1 FROM Market
WHERE ExternalId = #RegionId AND Id = I.MarketID)
OR I.MarketID = #MarketID

Get a parameter from one select clause instead of two

I want to get a parameter from a select clause in one time, instead of two selects.
Currently, I'm doing this :
SELECT
Idx_Pro,
Name,
Mail,
IsValidateUser
FROM
MyTable
WHERE
[Mail] = #Mail
AND
[Password] = #password
If (##ROWCOUNT > 0)
SET #Id_output = (SELECT Id_User
FROM MyTable
WHERE [Mail] = #Mail
AND [Password] = #password
)
I tried this :
DECLARE #Id_output int
SELECT
[#Id_output] = Idx_Pro,
...
FROM MyTable
...
But I can't get it ...
Is it even possible to get only one column in a variable ? (My select returns only one row)
thanks,
TonyFlow
Are you looking to both return the 4 column result and assign to the variable in one operation? If so that isn't possible. You could assign all the column values to variables or parameters then select those to return the result set though.
DECLARE #Idx_Pro INT,
#Name VARCHAR(50),
#IsValidateUser BIT
SELECT #Idx_Pro = Idx_Pro,
#Name = Name,
#IsValidateUser = IsValidateUser
FROM MyTable
WHERE [Mail] = #Mail
AND [Password] = #password
/*No intermediate statement can be placed here as it will reset ##ROWCOUNT*/
SELECT #Idx_Pro AS Idx_Pro,
#Name AS Name,
#Mail AS Mail,
#IsValidateUser AS IsValidateUser
WHERE ##ROWCOUNT > 0