i need your help again!
my query looks like this
Select * from USERS Where username = 'username1';
now i want to add some OR to the where clause:
Select * from USERS Where username = 'username1' OR username = 'username2';
the problem is must generate the query dynamical, because the selected user count is from 1 to 10;
i created a function that adds all user to a string
output:
'username = 'username1' OR username = 'username2''
i declare #names
and now my query looks like this:
DECLARE #names varchar(1000) = 'username = 'username1' OR username = 'username2''
Select * from USERS Where #names;
what is the right way to some OR's in the where clause?
thank you
Use IN()
SELECT *
FROM
USERS
WHERE
username IN('username1','username2')
Related
I'm trying to make an expression in SQL Server, that will check if certain column is null, and if it is null, set a new GUID number..
This is my code :
select
isnull((select Guid
from therapists
where username = 'ido' and password = 'ido'),
(update therapists
set guid = NEWID()
where username = 'ido' and password = 'ido'))
You can try this:
UPDATE therapists SET guid = NEWID()
WHERE username = 'ido'
AND password = 'ido'
AND guid IS NULL;
I am struggling to generate a 'notifications' query to work correctly at the moment.
I'm working on a query that will add a string to a table in which will add multiple rows at once, with only one column of which will be changed in this 'bulk insert':
I currently have:
public static void addNotification(string notification)
{
SqlConnection scon = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
using (SqlCommand scmd = new SqlCommand())
{
scmd.Connection = scon;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "INSERT INTO notificationAck (Email, Notification, isAcknowledged) VALUES ((SELECT Email FROM AspNetUsers), '" + notification + "' ,0)";
scon.Open();
int status = scmd.ExecuteNonQuery();
scon.Close();
}
}
However, on passing this a string like: "this is a notification", it comes up with the following error:
Subquery returned more than 1 value. This is not permitted when the
subquery follows =, !=, <, <= , >, >= or when the subquery is used as
an expression. The statement has been terminated.
So, could someone possibly explain how this query should be run?
The table has the columns:
I understand the 'PK1' isn't the best of practises, but this is only a table for testing purposes (it's set to auto increment)
So, the isAcknowledged should be set to 0, the notification should be this string, and the email should be selected from each row of the table AspNetUsers?
Would anyone e able to explain to me how I should go about adding this data into my db?
Something like this should work:
scmd.CommandText = "INSERT INTO notificationAck (Email,
Notification,
isAcknowledged)
SELECT Email, '" + notification + "', 0
FROM AspNetUsers";
INSERT INTO SELECT does not require VALUES. Hence, you only have to use a SELECT statement that retrieves Email field from AspNetUsers plus two constant values.
You don't want to use VALUES when using a query to generate your results. You can change the INSERT query to this:
INSERT INTO notificationAck (Email, Notification, isAcknowledged)
SELECT Email, 'SOME STRING', 0 FROM AspNetUsers
Which translated in to your code would look like:
scmd.CommandText = "INSERT INTO notificationAck (Email, Notification, isAcknowledged)
SELECT Email, '" + notification + "', 0 FROM AspNetUsers";
Select Top 1 in Sub Query if you want to insert only 1 row
try
INSERT INTO notificationAck (Email, Notification, isAcknowledged)
VALUES ((SELECT top 1 Email FROM AspNetUsers), '" + notification + "' ,0)
if you want to insert all rows from AspNetUsers then use
INSERT INTO notificationAck(Email,Notification, isAcknowledged) select
Email,''+notification +"',1 from AspNetUsers
Your query
SELECT Email FROM AspNetUsers
returns more than one row as your error says. You need to change it so that it returns only one row, for example:
SELECT TOP 1 Email FROM AspNetUsers
Then change your command as below
scmd.CommandText = "INSERT INTO notificationAck (Email, Notification, isAcknowledged) SELECT TOP 1 Email " + notification + "' ,0 FROM AspNetUsers'";
if you want to insert more than one row, the remove top 1 from query.
scmd.CommandText = "INSERT INTO notificationAck (Email, Notification, isAcknowledged) SELECT Email " + notification + "' ,0 FROM AspNetUsers'";
I am creating a report in SSRS that returns a bunch of data, one of the columns I need to return is a value from Active Directory. I have a query which gets a value that I want to pass into a subquery which looks a value up in Active Directory.
What I have so far looks something like this (simplified):
DECLARE #UserID int
SELECT #UserID = UserID FROM dbo.Users As TEST WHERE (RecordID = 123456)
(SELECT displayName FROM OpenQuery (
ADSI,
'SELECT displayName
FROM ''LDAP://DC=company,DC=local''
WHERE objectCategory=''user'' AND extensionattribute5='' +#UserID+ ''
') ) AS LoggedBy
FROM dbo.UserRecords WHERE UserID = 1
The problem is however when I use #UserID in the subquery the output alias "LoggedBy" always returns "Null". If I take the parameter out and manually type the value that the parameter has, it works fine.
It seems like I cannot get the #UserID paramter from the main query into the sub-query. ust wondering, what am I missing here?
You can't send variables into OpenQuery context in this way. Try to filter the query "outside":
DECLARE #UserID int
SELECT #UserID = UserID FROM dbo.Users As TEST WHERE (RecordID = 123456)
(SELECT t.displayName FROM OpenQuery (
ADSI,
'SELECT displayName, extensionattribute5
FROM ''LDAP://DC=company,DC=local''
WHERE objectCategory=''user''
') as t
WHERE t.extensionattribute5=#UserID ) AS LoggedBy
FROM dbo.UserRecords WHERE UserID = 1
From MSDN
OPENQUERY does not accept variables for its arguments.
By writing client server applications typically one stumbles in cases where he needs to do a query that returns different records according to which is the logged in user.
I use this approach, but I wonder if there are alternatives, may you suggest?
(the reason I ask is that for more complx queries this becomes quite unreadable, while with some CASE statements it would be better).
declare #UserIsAdministrator bit;
declare #UserID integer;
set #UserIsAdministrator = 0 -- test value
set #UserID = 41; -- test value
SELECT * FROM employees
WHERE
(#UserIsAdministrator = 1) -- if user is admin return all records
OR
(
(#UserIsAdministrator = 0)
AND
(manager_ID = #UserID)
) -- if user is not admin return only "his" records
I think I would try to avoid embedding this type of authorization within the SQL queries altogether. Have separate queries, and resolve roles and privileges in a separate layer/component before you select which query to execute.
Options:
IF and ELSE
IF #UserIsAdministrator = 1
SELECT * FROM employees
ELSE
SELECT * FROM employees WHERE manager_ID = #UserID
Change parameters based on another parameter
IF #UserIsAdministrator = 1
SET #UserID = NULL
SELECT * FROM employees
WHERE manager_ID = ISNULL(#UserID, manager_ID)
Or different views/stored procs
I am using asp .net web form search in c#, for example with fields:
- name
- fruit
I want to write a sproc that can search name or fruit. If I knew that both would have values, I would pass two parameters into the sproc and would write:
Select * from myTable where name =#name and fruit = #fruit
However sometimes, either name or fruit could be empty. Without writing a separate search for fruit and name. How would I achieve this?
I would prefer not to create a dynamic query if possible, but if this is the only way how would I write it?
You'll need to make sure that empty strings aren't passed as arguments instead of null, but the following should work. I'm pretty sure, though, that if the user doesn't input anything the form value will be null.
select * from myTable
where (#name is null or name = #name) and (#fruit is null or fruit = #fruit)
maybe:
SELECT * FROM myTable WHERE name Like '%' + #name AND fruit LIKE '%' + #fruit
select * from myTable
where
(name = #name and fruit = #fruit)
or (name = #name and #fruit is null)
or (fruit = #fruit and #name = is null )
select * from myTable where name = isnull(#name, name) and fruit = isnull(#fruit, fruit)
Will return the entire table if both #name and #fruit is null. If that is a problem, you better add some additional logic to the SP.