Get a parameter from one select clause instead of two - sql

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

Related

SQL query to retrieve data based on either emailid or userid

I have to write a query for a login page where the user can enter either emailid(varchar datatype) or userid(int datatype). How do I write a query for this without knowing the datatype of the input?
CREATE PROCEDURE my_stored_procedure
#emailId nvarchar(50) = NULL,
#userId int = NULL
AS
SET NOCOUNT ON;
IF (#emailId IS NOT NULL) AND (LEN(#emailId) > 0)
SELECT * FROM MYTABLE WHERE EmailId = #emailId
ELSE
SELECT * FROM MYTABLE WHERE UserId = #UserId
GO
Your input parameter should be of varchar type.
Then in your procedure use ISNUMERIC function to check for number. Have two queries based on that with IF statement in case if it is int or varchar.
DECLARE #userInput VARCHAR(50)
IF ISNUMERIC(#userInput) = 1
BEGIN
-- Your query with userid
END
ELSE
BEGIN
-- Your query with emailid
END
Try this query it may help you.
DECLARE #emailid varchar(250),#userid bigint
set #emailid='A'
SET #userid=3
select * from yourtable
where case when #emailid='A' THEN 'A' ELSE emailid END=#emailid
AND case when #userid=0 THEN 0 ELSE userid END=#userid
Note: You should pass 'A' as default value for email_id and 0 for userid or else you can pass your required input

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

SQL Server Stored Procedure Check if Record Exists Before Insert

I am doing a check to see if a record exists before inserting it into a table (and this method seems to work on other stored procedures I am already using) but for this particular stored procedure it is not inserting anything even though the table is empty, why not?
CREATE PROCEDURE spInsertMovieHasTrailer
#movieID int,
#name varchar(50)
AS
BEGIN
SELECT #name = name, #movieID = movieID
FROM MovieHasTrailer
WHERE name = #name and movieID = #movieID
IF #name IS NULL and #movieID IS NULL
BEGIN
INSERT INTO MovieHasTrailer
(
movieID,
name
)
Values (
#movieID,
#name
)
END
END
Executing like this:
execute spInsertMovieHasTrailer 1, 'Test'
I would build this directly into the insert and not use if logic. if introduces race conditions:
INSERT INTO MovieHasTrailer
SELECT movieID, name
FROM (SELECT #movieID as movieID, #name as name) t
WHERE NOT EXISTS (SELECT 1
FROM MovieHasTrailer mht
WHERE mht.MovieId = t.MovieID AND mht.name = t.name
);
Note that this assumes that you need both the id and name to match the movie. I would think the id would be sufficient.
Also, what I would really do is have a unique index on either MovieHasTrailer(MovieId) or MovieHasTrailer(MovieId, Name). Then use a try/catch block if there is an insert error.
your select into variable may returns more than one value and you get error, it's better to use if not exists:
IF NOT EXISTS
(
SELECT name, movieID
FROM MovieHasTrailer
WHERE name = #name and movieID = #movieID
)
BEGIN
INSERT INTO MovieHasTrailer
(
movieID,
name
)
Values (
#movieID,
#name
)
END
The reason you are not doing an insert is the following code will not change the value of #name and #movieID if the query returns no records
SELECT #name = name, #movieID = movieID
FROM MovieHasTrailer
WHERE name = #name and movieID = #movieID
Whatever value for #name and #movieID you are passing into the stored procedure remain unchanged. I assume you are not passing in null values so the IF block is never executed.
You can try this way also you can achieve your goal and it save your time also.
INSERT INTO MovieHasTrailer
SELECT #movieID as movieID, #name as name
except
select MovieId, name
FROM MovieHasTrailer mht
where MovieId = #MoveID
I would do this by standart MERGE statement:
Create table t(id int, name nvarchar(max))
Declare #id int = 1, #name nvarchar(max) = 'Mission imposible'
Merge t using (select #id, #name) as s(id, name)
on t.id = s.id
when not matched then
insert(id, name) values(s.id, s.name);
You can also add WHEN MATCHED THEN UPDATE, WHEN NOT MATCHED BY SOURCE THEN DELETE to this statement.
Fiddle: http://sqlfiddle.com/#!6/c2569/23
try this :
CREATE PROCEDURE spInsertMovieHasTrailer
#movieID int,
#name varchar(50)
AS
BEGIN
declare #rowStatus nvarchar(50)=null
set #rowStatus=(SELECT name FROM MovieHasTrailer WHERE name = #name and movieID = #movieID)
IF (#rowStatus is NULL)
BEGIN
INSERT INTO MovieHasTrailer
(
movieID,
name
)
Values (
#movieID,
#name
)
END
END

assigning results of sql query to local variables

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

How to return default value from SQL query

Is there any easy way to return single scalar or default value if query doesn't return any row?
At this moment I have something like this code example:
IF (EXISTS (SELECT * FROM Users WHERE Id = #UserId))
SELECT Name FROM Users WHERE Id = #UserId
ELSE
--default value
SELECT 'John Doe'
How to do that in better way without using IF-ELSE?
Assuming the name is not nullable and that Id is unique so can match at most one row.
SELECT
ISNULL(MAX(Name),'John Doe')
FROM
Users
WHERE
Id = #UserId
Try ISNULL or COALESCE:
SELECT ISNULL((SELECT TOP 1 Name FROM Users WHERE Id = #UserId), 'John Doe')
The inner select will return nothing if no user exist with this id, the isnull will solve this case.
Try this
SELECT IFNULL(Name,'John Doe')
FROM Users
WHERE Id = #UserId)
You can drop the if statement using following construct but that doesn't necessarely mean it is better.
SELECT Name FROM Users WHERE Id = #UserId UNION ALL
SELECT 'John Doe' WHERE NOT EXISTS (SELECT Name FROM Users WHERE Id = #UserId)
Try isnull
SELECT IsNULL(Name, 'John Doe') FROM Users WHERE Id = #UserId
Edit:
drop table users
go
create table users
(id int,name varchar(20))
go
insert into users select 1,'1'
go
declare #userid int
set #userid = 1
select isnull(username.username, 'John Doe')
from (select #userid as userid) userid
outer apply (SELECT name as username FROM Users WHERE Id = userid.userid ) username
--outer apply (SELECT name as username FROM Users WHERE Id = #userid ) username
I suppose you could use ##ROWCOUNT to see if any will be returned.
SELECT Name FROM Users WHERE Id = #UserId
if(##ROWCOUNT = 0)
SELECT 'John Doe'
You could also use a variable if you're expecting one row.
declare #name varchar(100)
set #name = (select top 1 name from users where id = #userId)
if(#name is null) set #name = 'John Doe'
select #name
I would suggest that the best way to do is that first declare #name . Then set this value based on user id and then if #name is null show default name otherwise show name... That method would be as efficient as any other method and will be more readable.for other methods any other user to have think a lot to know what is going on unless there is nice comment.
declare #userid int
set #userid = 1
select isnull(
(select name from users where id = #userid),
'John Doe'
)
go
--My preffered would be this one..
declare #name varchar(20),#userid int
set #userid = 1
select #name = name from users where id = #userid
select isnull(#name,'John Doe')
If the query is supposed to return at most one row, use a union with the default value then a limit:
SELECT * FROM
(
SELECT Name FROM Users WHERE Id = #UserId`
UNION
SELECT 'John Doe' AS Name --Default value
) AS subquery
LIMIT 1
Both the query and default can have as many columns as you wish, and you do not need to guarantee they are not null.