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;
Related
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')
I am new to Dapper, so I may be missing something obvious but I don't understand why this query is returning null even though the record exists in the table.
queryResult = db.Query<dynamic>(#"SELECT Id FROM Customer WHERE CustomerId = #CustomerId",
new { CustomerId = theCustomerId }).FirstOrDefault();
I am checking to see if the record exists and in this case it does, yet queryResult is always null. The #CustomerId parameter is a string that I am matching exactly..
If I run the SQL in SQL Server is brings up the record no problem ...
SELECT Id FROM Customer WHERE CustomerId = 'abc123'
where abc123 is the CustomerId
It returns null as you want it to do so
Following is your query getting executed, as part of Query API
"SELECT Id FROM Customer WHERE CustomerId = #CustomerId",
new { CustomerId = theCustomerId }
Now what happens when CustomerId doesn't match, it produces empty IEnumerable<dynamic>, though its a different story why dynamic, you shall use integer assuming Id is an integer
but what FirstOrDefault() does on finding an empty IEnumerable, returns null, so simply remove it do check like Any, dapper by default doesn't return null, your code is forcing it
Best way to check for existence using dapper would be:
string sql = "SELECT count(1) FROM Customer WHERE CustomerId = #CustomerId;";
bool exists = false;
using (var connection = new SqlConnection("connection string"))
{
connection.Open();
exists = connection.ExecuteScalar<bool>(sql, new { CustomerId = "abc123" });
}
As to why your specific example returns null, I suspect it's because you needed brackets around the db.Query like:
queryResult = (db.Query<dynamic>(#"SELECT Id FROM Customer WHERE CustomerId = #CustomerId",
new { CustomerId = theCustomerId })).FirstOrDefault();
Lets say i have two tables with almost the same structure
TableFrom
ID bigint
Username nvarchar
Password nvarchar
Name nvarchar
TableTo
ID bigint
Username nvarchar
Password nvarchar
Now i want to generate an Insert into SQL query ( using parameters ) but only for those fields who are the same in both tables. ( id, username, password )
I thought about reading those two table structure queries into dataTable and after that loop with LINQ to get array of fields which are the same in bot tables ?
Dim dtFrom as new datatable
dim dtTo as NEW dataTable
dtTo = _LoadAvaliableToFields()
dtFrom = _loadAvailableFromFields()
How would that LINQ go ?
After that i need to add the Insert query to database using parameters. Is there any simpler way to do this ?
Using query syntax the "select" query would be very similar to a SQL query:
Dim query =
From idFrom In TableFrom _
Join idTo In TableTo _
On New With {Key .ID = idFrom.ID, Key .U = idFrom.Username, Key .P = idFrom.Password} _
Equals New With {Key .ID = idTo.ID, Key .U = idTo.Username, Key .P = idTo.Password} _
Select idFrom
To do an insert you'd need to add objects to the appropriate collections in the context, then call SaveChanges.
I would note that a direct SQL query would be more efficient:
INSERT INTO {destination}
SELECT f.ID,f.Username,f.Password
FROM TableFrom f
INNER JOIN TableTo t
ON f.ID = t.ID AND f.Username = t.Username AND f.Password = t.Password
I have created a SQL Server table that uses uniqueidentifier as the primary key. I set the Default Value or Binding to newid(). (I would like to set the Identity Specification for this column, but that isn't supported for uniqueidentifier types.)
I'm then using ADO.NET to add a row to this table.
SqlComment command = new SqlCommand("INSERT INTO [User] (Name) VALUES (#name);
SELECT SCOPE_IDENTITY()", Connection);
command.Parameters.AddWithValue("#name", "Joe Smoe");
Guid userId = (Guid)command.ExecuteScalar();
However, the last line fails because ExecuteScaler() returns null. It appears that, since a uniqueidentifier cannot be the table's identity, SCOPE_IDENTITY() returns null (as does ##IDENTITY).
Okay, so is there another way to retrieve the newly added ID using ADO.NET?
SCOPE_IDENTITY() is only used for Identity value, for guid values you would need to use the OUTPUT clause with a table variable.
DECLARE #NewGuid TABLE(NewValue UNIQUEIDENTIFIER);
INSERT INTO [User] (Name)
OUTPUT inserted.pk_ColName INTO #NewGuid(NewValue)
VALUES (#name);
SELECT * FROM #NewGuid --<-- here you will have the new GUID Value
C# code would look something like....
string cmd = "DECLARE #NewGuid TABLE(NewValue UNIQUEIDENTIFIER);
INSERT INTO [User] (Name)
OUTPUT inserted.pk_ColName INTO #NewGuid(NewValue)
VALUES (#name);
SELECT #newID = NewValue FROM #NewGuid;"
SqlCommand command = new SqlCommand(cmd, Connection);
cmd.Parameters.AddWithValue("#name", "Joe Smoe");
cmd.Parameters.Add("#newID", SqlDbType.UniqueIdentifier).Direction = ParameterDirection.Output;
Guid userId = (Guid)cmd.ExecuteScalar();
Personally I would put the whole thing in a stored procedure.
Scope_Identity() focuses on an IDENTITY field, so it will never yield anything. You need to output from INSERTED instead. Even though this page is not focused on your particular problem, it should give you some clues:
Return ID on INSERT?
My normal direction is a stored procedure, but you can chain commands, as you have done. The stored procedure makes things a bit easier, as you can create an output parameter for the procedure, but outputting a value works fine.
EDITED to show specific example:
Assume the following table:
CREATE TABLE [dbo].[MyTable]
(
[Id] [uniqueidentifier] PRIMARY KEY NOT NULL DEFAULT NEWID(),
[Name] [varchar](50) NOT NULL,
)
The following program will output the new GUID created from NewID():
class Program
{
static void Main(string[] args)
{
var connString = ConfigurationManager.ConnectionStrings["testDB"].ToString();
var cmdString = "INSERT INTO MyTable (Name) OUTPUT Inserted.Id VALUES ('Name')";
var connection = new SqlConnection(connString);
var command = new SqlCommand(cmdString, connection);
Guid outputValue;
try
{
connection.Open();
//Convert to Guid here instead
Console.WriteLine(command.ExecuteScalar().ToString());
}
finally
{
connection.Dispose();
}
Console.Read();
}
}
##IDENTITY returns the ID of the last row inserted, I want to retrieve the ID of the last row updated.
Here is my query:
UPDATE [Table]
SET Active = 1,
Subscribed = 1,
RenewDate = GETDATE(),
EndDate = DATEADD(mm,1,getdate()),
WHERE SC = #SC
AND Service = #Ser
How do I get the ID of this updated row?
The column is called TableID and I'm not using it in the query.
You cannot retrieve an ID since there is no ID being inserted.....
But you can:
just query the table using the same criteria as in your UPDATE:
SELECT TableID
FROM dbo.Table
WHERE SC = #SC AND Service = #Ser -- just use the same criteria
use the OUTPUT clause on the UPDATE to get that info:
UPDATE [Table]
SET Active = 1,
Subscribed = 1,
RenewDate = GETDATE(),
EndDate = DATEADD(mm,1,getdate())
OUTPUT Inserted.TableId -- output the TableID from the table
WHERE SC = #SC AND Service = #Ser
Read more about the OUTPUT clause on Technet - it can be used on INSERT and DELETE as well
you can try using this:
OUTPUT INSERTED.TableID
in your code it would look like this:
UPDATE [Table]
SET Active = 1,
Subscribed = 1,
RenewDate = GETDATE(),
EndDate = DATEADD(mm,1,getdate())
OUTPUT INSERTED.TableID
WHERE SC = #SC
AND Service = #Ser
Hope this helps.
I guess you need this one,
UPDATE [Table]
SET Active = 1,
Subscribed = 1,
RenewDate = GETDATE(),
EndDate = DATEADD(mm,1,getdate())
OUTPUT INSERTED.TABLE_PrimaryKeyID
WHERE SC = #SC
AND Service = #Ser
Main source: here
Try using
select ##identity gives last updated identity for the particular session
(or)
select scope_identity gives last updated identity for the particular scope
(or)
select ident_curr('tablename') give the last updated identity regardless of the session or scope but for that particular table.