I have an assignment table in my database. I also have a assignment_notes table, which has a reference to the assignment table. There can exists multiple rows in this table.
When I select all my assignments, I want to check if there exists some notes to this assignment. And all I want is a true/false return.
Is it possible to do something like (pseudo):
Select all assignments; if assignment
has assignment_notes HasNotes = true; else
HasNotes = false.
I hope I made this clear enough - I'm not so good at explaining programming stuff ;-)
DECLARE #Assignments TABLE
(
Id INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Name VARCHAR(30) NOT NULL
)
DECLARE #AssignmentNotes TABLE
(
Id INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
AssignmentId INT NOT NULL,
Note VARCHAR(MAX)
)
INSERT INTO #Assignments(Name) VALUES('Biology')
INSERT INTO #Assignments(Name) VALUES('Chemistry')
INSERT INTO #AssignmentNotes (AssignmentId, Note) VALUES(1, 'Studies on DNA')
INSERT INTO #AssignmentNotes (AssignmentId, Note) VALUES(1, 'Evolution notes from Darwin')
SELECT
A.*,
CASE WHEN COUNT(AN.Id) > 0 THEN 1 ELSE 0 END AS HasNotes
FROM
#Assignments AS A
LEFT JOIN
#AssignmentNotes AS AN
ON A.Id = AN.AssignmentId
GROUP BY
A.Id,
A.Name
Don't have SQL Server ready to test, but a query like this should work:
SELECT A.*,
CAST(
CASE (SELECT TOP 1 AssignmentNotes_ID
FROM AssignmentNotes AN
WHERE AN.AssignmentID = A.AssignmentID)
WHEN NULL THEN 0 ELSE 1 END
AS BIT) AS HasNotes
FROM Assignments A
SELECT a.*,
(SELECT COUNT(*)
FROM assignment_notes an
WHERE an.assignmentid = a.id) as NumNotes
FROM Assignment a
That will give you the number of notes with that assignment.
You can translate your pseudo code to SQL if you use the case statement. On MSDN: http://msdn.microsoft.com/en-us/library/ms181765.aspx
And another article just in case: http://www.devx.com/tips/Tip/15633
This approach means that you don't need a huge GROUP BY statement as a result of returning lots of Assignment fields.
SELECT Assignment.*,
CAST(CASE WHEN NotesQty>0 THEN 1 ELSE 0 END as bit) AS HasNotes
FROM Assignment
LEFT JOIN
(SELECT AssignmentId,COUNT(*) AS NotesQty
FROM assignment_notes
GROUP BY AssignmentId) as Assignment_NotesQty
ON Assignment_NotesQty.AssignmentId=Assignment.AssignmentId
Related
I have a list of teams in one table and list of cases in another table. I have to allocate a unique random case number to each one of the members in the team. What is the best way to generate unique random case number for each team member. I have read about NewID() and CRYPT_GEN_RANDOM(4) functions. I tried using them but not getting unique number for each team member. Can some one please help me. Thanks for your time. I am using SQL 2008.
I have a 'Teams' table which has team members, their ids(TM1,TM2 etc.) and their names.
I have another 'Cases' table which has ID numbers like 1,2,3,4 etc. I want to allocate random case to each team member. The desired output should be as below.
Team member Random_case_allocated
TM1 3
TM2 5
TM3 7
TM4 2
TM5 8
TM6 6
I have tried
SELECT TOP 1 id FROM cases
ORDER BY CRYPT_GEN_RANDOM(4)
It is giving the same id for all team members. I want a different case id for each team member. Can someone please help. Thank you.
The TOP(1) ORDER BY NEWID() will not work the way you are trying to get it to work here. The TOP is telling the query engine you are only interested on the first record of the result set. You need to have the NEWID() evaluate for each record. You can force this inside of a window function, such as ROW_NUMBER(). This could optimized I would imagine, however, it was what I could come up with from the top of my head. Please note, this is not nearly a truly random algorithm.
UPDATED With Previous Case Exclusions
DECLARE #User TABLE(UserId INT)
DECLARE #Case TABLE(CaseID INT)
DECLARE #UserCase TABLE (UserID INT, CaseID INT, DateAssigned DATETIME)
DECLARE #CaseCount INT =10
DECLARE #SaveCaseID INT = #CaseCount
DECLARE #UserCount INT = 100
DECLARE #NumberOfUserAllocatedAtStart INT= 85
WHILE(#CaseCount > 0)BEGIN
INSERT #Case VALUES(#CaseCount)
SET #CaseCount = #CaseCount-1
END
DECLARE #RandomCaseID INT
WHILE(#UserCount > 0)BEGIN
INSERT #User VALUES(#UserCount)
SET #UserCount = #UserCount-1
IF(#NumberOfUserAllocatedAtStart > 0 )BEGIN
SET #RandomCaseID = (ABS(CHECKSUM(NewId())) % (#SaveCaseID))+1
INSERT #UserCase SELECT #UserCount,#RandomCaseID,DATEADD(MONTH,-3,GETDATE())
SET #RandomCaseID = (ABS(CHECKSUM(NewId())) % (#SaveCaseID))+1
INSERT #UserCase SELECT #UserCount,#RandomCaseID,DATEADD(MONTH,-5,GETDATE())
SET #RandomCaseID = (ABS(CHECKSUM(NewId())) % (#SaveCaseID))+1
INSERT #UserCase SELECT #UserCount,#RandomCaseID,DATEADD(MONTH,-2,GETDATE())
SET #NumberOfUserAllocatedAtStart=#NumberOfUserAllocatedAtStart-1
END
END
;WITH RowNumberWithNewID AS
(
SELECT
U.UserID, C.CaseID, UserCase_CaseID = UC.CaseID,
RowNumber = ROW_NUMBER() OVER (PARTITION BY U.UserID ORDER BY NEWID())
FROM
#User U
INNER JOIN #Case C ON 1=1
LEFT OUTER JOIN #UserCase UC ON UC.UserID=U.UserID AND UC.CaseID=C.CaseID AND UC.DateAssigned > DATEADD(MONTH, -4, UC.DateAssigned)
WHERE
UC.CaseID IS NULL OR UC.CaseID <> C.CaseID
)
SELECT
UserID,
CaseID,
PreviousCases = STUFF((SELECT ', '+CONVERT(NVARCHAR(10), UC.CaseID) FROM #UserCase UC WHERE UC.UserID=RN.UserID FOR XML PATH('')),1,1,'')
FROM RowNumberWithNewID RN
WHERE
RN.RowNumber=1
I am not sure this is possible, but here is what I am trying to do: In the where clause below it is working fine but now I need to somehow:
If #Contact has a value of 'Steve' but 'Steve' does not exist in contact I want to return records where contact is null.
How can I achieve that?
WHERE (contact = #Contact OR (contact IS NULL AND #Contact IS NULL))
One method uses a subquery. A version that doesn't use a subquery is:
select top (1) with ties t.*
from t
where contact = #Contact or contact is null
order by contact desc;
I'm guessing a bit on exactly what you are after, but one possibility might be something like this?
select * from someTable t
where 1 =
(case when exists(select * from someTable t2 where t2.contact = #contact)
then
case when #contact = t.contact then 1 end
else
case when t.contact IS NULL then 1 end
end)
This means:
IF at least one row exists in someTable, where someTable.contact = #contact,
then return all rows where someTable.contact = #contact .
Otherwise, return all rows where someTable.contact IS NULL.
If you set it up as a stored procedure, you can set the default to a blank and then use that in the WHERE statement. Below is a pseudo-example from a working proc. It uses a Full-Text Index but you get the idea.
CREATE PROCEDURE [dbo].[procMyProc]
#p_searchtermKeyword NVARCHAR(255) = '""'
AS
BEGIN
SET NOCOUNT ON;
SELECT *
FROM MyTable
WHERE ((CONTAINS(Keywords, #p_searchtermKeyword)) OR #p_searchtermKeyword = '""')
END
Could someone help me to understand the logic of this query (T-SQL in SQL Server 2014) in simple way?
Select
c.ContractID
From
dba.contract as c
Inner Join
dba.Person as r on (c.ContractID = r.ContractID
and IsNull(isPrimary, 0) = 1)
The part that I dont understand is the isNull(isPrimary, 0) = 1.
What does that mean? Btw isPrimary is one of the columns in dba.person
Thank you so much!
isNull(isPrimary, 0) = 1
isNull is a function of SQL which is used to verify null variable
and above snippet describe as if isPrimary variable is null then replace this null value with 0. the purpose of this method to handle null pointer exception.
If you want to watch how it works, you can create table in your database:
use [your_database_name];
create table dbo.test_table
(
t int null
);
insert into dbo.test_table
values (0), (1), (2), (NULL);
select t, isnull(t, 0) as function_result
from dbo.test_table
Sample script for you to understand IsNull(isPrimary, 0) = 1 condition gives
the result and helps in handling Null pointer exception.
DECLARE #table AS TABLE (Id int, isPrimary varchar(20))
INSERT INTO #table
SELECT 1,1001 UNION ALL
SELECT 2,1002 UNION ALL
SELECT 3,NULL UNION ALL
SELECT 4,1004
SELECT Id,ISNULL(isPrimary,0) UIdnum FROM #table
SELECT * FROM #table WHERE ISNULL(isPrimary,0)=1
SELECT * FROM #table WHERE ISNULL(isPrimary,0)=0
The IS_NULL function is only replacing the value of isPrimary to 0, in case the isPrimary is equal to NULL.
Your check is only true when isPrimary is not null (because if it is, it will be replaced by 0) AND isPrimary = 1.
SELECT c.contractid
FROM dba.contract AS c
INNER JOIN dba.person AS r ON (c.contractid = r.contractid AND isprimary = 1)
WHERE isprimary IS NOT NULL
Using SQL Server 2000; I am trying to determine the action if a value in a field of the INSERTED record matches one of several distinct values in a field in a table. Field y in tableB could be say 'one', 'two' or 'three'. The INSERTED record must be a single record, and therefore the field x must be a single value. Hence, given the code snippet below, what is the correct syntax? In particular where do the "()" go in the IF statement?
if select x from INSERTED in (select y from tableB)
and <another condition>
begin
<some code>
end
The correct syntax is
IF EXISTS (SELECT * FROM TABLE1 WHERE X IN (1,2))
Begin
-- code
End
You can store the individual flag in variables and use that in IF condition.
Declare #chkExist int
Select #chkExist = Count(*) from tableA x in (select y from tableB)
if ((#chkExist > 0) and (<another condition>))
begin
<some code>
end
Try a "where exists" instead of "IN"
if exists ( select null from tableA taAlias where (select null from tableB tbAlias where tbAlias.y = taAlias.x ) )
and 1=1
begin
Select 1 as 'YouNeedAtLeastOneLineOfCodeInThisBeginEnd'
end
I know we can use LIKE for pattern matching, however, here is what want to do.
I have a table, which has a column, 'Pattern', the values are like:
host1%
%host2
....
I have another table, which has a column, 'Host'. The question is: how can I check whether the values in 'Host' table do not match any patterns in 'Pattern'?
If it is too complex, then a simplified question is: How can I check whether the values in 'Host' do not StartWith any strings in 'Pattern'?
We can use loop, but is there a better way? ideally, it should work for ql server 2008, but latest version will do.
thanks
Use where not exists followed by a subquery which checks each pattern against the current row of the table containing your data. i.e.
where not exists
(
select top 1 1
from #patterns p
where d.datum like p.pattern
)
Full Code for Working Example: SQL Fiddle
declare #patterns table
(
pattern nvarchar(16) not null
)
declare #data table
(
datum nvarchar(16) not null
)
insert #patterns
values ('host1%')
,('%host2')
insert #data
values ('host1234')
, ('234host1')
, ('host2345')
, ('345host2')
select *
from #data d
where not exists
(
select top 1 1
from #patterns p
where d.datum like p.pattern
)
select t1.host
from table_1 t1
left join table_2 t2 on t1.host like t2.pattern
where t2.pattern is null