Showing posts with label exists. Show all posts
Showing posts with label exists. Show all posts

Wednesday, March 28, 2012

MS SQL Server Return 1 if exists?

I'm trying to return data from a query and I can't even begin to wrap my head around what I need to do to get started.

I have two tables:

TableOne
col_deptName
col_deptID

TableTwo
col_userName
col_userid
col_permissionDeptName

I want to return all rows in TableOne and 1 or 0 in based on whether TableTwo.col_permissionDeptName = TableOne.col_deptName

Such that the output would look like:

"Department" "Enabled"
------ ------
dept1 0
dept2 1
dept3 0
dept4 1
dept5 1
dept6 1

Quote:

Originally Posted by jinksto

I'm trying to return data from a query and I can't even begin to wrap my head around what I need to do to get started.

I have two tables:

TableOne
col_deptName
col_deptID

TableTwo
col_userName
col_userid
col_permissionDeptName

I want to return all rows in TableOne and 1 or 0 in based on whether TableTwo.col_permissionDeptName = TableOne.col_deptName

Such that the output would look like:

"Department" "Enabled"
------ ------
dept1 0
dept2 1
dept3 0
dept4 1
dept5 1
dept6 1


Try this...

SELECT col_deptID AS DEPTID,col_deptName AS DEPARTMENT,
CASE ISNULL(col_permissionDeptName,'') WHEN '' THEN 0
ELSE 1 END AS ENABLED
FROM TableOne LEFT JOIN TableTwo
ON col_deptName = col_permissionDeptName|||

Quote:

Originally Posted by vijaii

Try this...

SELECT col_deptID AS DEPTID,col_deptName AS DEPARTMENT,
CASE ISNULL(col_permissionDeptName,'') WHEN '' THEN 0
ELSE 1 END AS ENABLED
FROM TableOne LEFT JOIN TableTwo
ON col_deptName = col_permissionDeptName


That almost works but unfortunately col_permissionDeptName will never be null.

TableTwo
col_userName
col_userid
col_permissionDeptName

Table two rows look like this:

col_userName col_userid col_permissionDeptName
userJoe user1 dept1
userbob user2 dept1
userbob user2 dept2
usermike user3 dept1
usermike user3 dept3

... so this is just a list of users and departments that they have access to and doesn't have the complete list of departments.|||

Quote:

Originally Posted by jinksto

That almost works but unfortunately col_permissionDeptName will never be null.

TableTwo
col_userName
col_userid
col_permissionDeptName

Table two rows look like this:

col_userName col_userid col_permissionDeptName
userJoe user1 dept1
userbob user2 dept1
userbob user2 dept2
usermike user3 dept1
usermike user3 dept3

... so this is just a list of users and departments that they have access to and doesn't have the complete list of departments.


I used left join so if there is dept name in Tableone and not in tabletwo then the
permissionDeptName in tabletwo will be null.If you are not clear about this please refer the Left Join in the SQL help|||

Quote:

Originally Posted by vijaii

I used left join so if there is dept name in Tableone and not in tabletwo then the
permissionDeptName in tabletwo will be null.If you are not clear about this please refer the Left Join in the SQL help


You're right, of course. Sorry about that, I misread it.

Unfortunately, I think I explained what I wanted incorrectly.

I want to return the complete list by T2.col_userid with a 1 or a 0 to indicate which departments

So, essentially, for user1 I want to return a list of all departments along with a 1 or a 0 indicating whether T2.col_permission exists for user1

Sorry if I'm not explaining what I want correct. Thanks for your help.|||

Quote:

Originally Posted by jinksto

You're right, of course. Sorry about that, I misread it.

Unfortunately, I think I explained what I wanted incorrectly.

I want to return the complete list by T2.col_userid with a 1 or a 0 to indicate which departments

So, essentially, for user1 I want to return a list of all departments along with a 1 or a 0 indicating whether T2.col_permission exists for user1

Sorry if I'm not explaining what I want correct. Thanks for your help.


Just do what Vijaii said but with a WHERE col_userid = 'user1'|||

Quote:

Originally Posted by DonlonP

Just do what Vijaii said but with a WHERE col_userid = 'user1'


If I do that then it only returns values from the left table where there's an equivalent right table entry... So I only ever get 1's and no 0's

I want all values from left table and 1 if an equivalent value exists in right table and 0 if null.|||

Quote:

Originally Posted by jinksto

If I do that then it only returns values from the left table where there's an equivalent right table entry... So I only ever get 1's and no 0's

I want all values from left table and 1 if an equivalent value exists in right table and 0 if null.


Can you give an example with data for TableOne,TableTwo and the Final Result
i.e. what should be the outcome Result by joining TableOne and TableTwo? so that I can help you better.

Monday, March 19, 2012

MS SQL security best practices?

Hi all,
Is there a document exists that identifies/discusses/lists security best
practices for MS SQL Server?
Any info. will be appreciated.
Plese, post reply to this msg.
Thanks in Advance.
-MsdTry SQLSecurity.com
I do have an article on my site:
http://vyaskn.tripod.com/sql_server_security_best_practices.htm but I
haven't updated it recently.
--
HTH,
Vyas, MVP (SQL Server)
http://vyaskn.tripod.com/
Is .NET important for a database professional?
http://vyaskn.tripod.com/poll.htm
"MSD" <no@.spam> wrote in message
news:Xns9499B11D0EF8Anospam@.207.46.248.16...
Hi all,
Is there a document exists that identifies/discusses/lists security best
practices for MS SQL Server?
Any info. will be appreciated.
Plese, post reply to this msg.
Thanks in Advance.
-Msd|||Hi,
Look into this article as well on "Implementation of Server Level Security
and Object Level Security"
http://www.microsoft.com/technet/treeview/default.asp?url=/technet/prodtechn
ol/sql/maintain/security/sp3sec/SP3SEC02.ASP
Thanks
Hari
MCDBA
"Narayana Vyas Kondreddi" <answer_me@.hotmail.com> wrote in message
news:OVq$v2y#DHA.3500@.tk2msftngp13.phx.gbl...
> Try SQLSecurity.com
> I do have an article on my site:
> http://vyaskn.tripod.com/sql_server_security_best_practices.htm but I
> haven't updated it recently.
> --
> HTH,
> Vyas, MVP (SQL Server)
> http://vyaskn.tripod.com/
> Is .NET important for a database professional?
> http://vyaskn.tripod.com/poll.htm
>
>
> "MSD" <no@.spam> wrote in message
> news:Xns9499B11D0EF8Anospam@.207.46.248.16...
> Hi all,
> Is there a document exists that identifies/discusses/lists security best
> practices for MS SQL Server?
> Any info. will be appreciated.
> Plese, post reply to this msg.
> Thanks in Advance.
> -Msd
>|||Lots of stuff on the SQL site
http://www.microsoft.com/sql/techinfo/administration/2000/security/default.asp
--
HTH
Jasper Smith (SQL Server MVP)
I support PASS - the definitive, global
community for SQL Server professionals -
http://www.sqlpass.org
"MSD" <no@.spam> wrote in message
news:Xns9499B11D0EF8Anospam@.207.46.248.16...
> Hi all,
> Is there a document exists that identifies/discusses/lists security best
> practices for MS SQL Server?
> Any info. will be appreciated.
> Plese, post reply to this msg.
> Thanks in Advance.
> -Msd

MS SQL security best practices?

Hi all,
Is there a document exists that identifies/discusses/lists security best
practices for MS SQL Server?
Any info. will be appreciated.
Plese, post reply to this msg.
Thanks in Advance.
-MsdTry SQLSecurity.com
I do have an article on my site:
http://vyaskn.tripod.com/sql_server...t_practices.htm but I
haven't updated it recently.
--
HTH,
Vyas, MVP (SQL Server)
http://vyaskn.tripod.com/
Is .NET important for a database professional?
http://vyaskn.tripod.com/poll.htm
"MSD" <no@.spam> wrote in message
news:Xns9499B11D0EF8Anospam@.207.46.248.16...
Hi all,
Is there a document exists that identifies/discusses/lists security best
practices for MS SQL Server?
Any info. will be appreciated.
Plese, post reply to this msg.
Thanks in Advance.
-Msd|||Hi,
Look into this article as well on "Implementation of Server Level Security
and Object Level Security"
http://www.microsoft.com/technet/tr...chnet/prodtechn
ol/sql/maintain/security/sp3sec/SP3SEC02.ASP
Thanks
Hari
MCDBA
"Narayana Vyas Kondreddi" <answer_me@.hotmail.com> wrote in message
news:OVq$v2y#DHA.3500@.tk2msftngp13.phx.gbl...
> Try SQLSecurity.com
> I do have an article on my site:
> http://vyaskn.tripod.com/sql_server...t_practices.htm but I
> haven't updated it recently.
> --
> HTH,
> Vyas, MVP (SQL Server)
> http://vyaskn.tripod.com/
> Is .NET important for a database professional?
> http://vyaskn.tripod.com/poll.htm
>
>
> "MSD" <no@.spam> wrote in message
> news:Xns9499B11D0EF8Anospam@.207.46.248.16...
> Hi all,
> Is there a document exists that identifies/discusses/lists security best
> practices for MS SQL Server?
> Any info. will be appreciated.
> Plese, post reply to this msg.
> Thanks in Advance.
> -Msd
>|||Lots of stuff on the SQL site
http://www.microsoft.com/sql/techin...www.sqlpass.org
"MSD" <no@.spam> wrote in message
news:Xns9499B11D0EF8Anospam@.207.46.248.16...
> Hi all,
> Is there a document exists that identifies/discusses/lists security best
> practices for MS SQL Server?
> Any info. will be appreciated.
> Plese, post reply to this msg.
> Thanks in Advance.
> -Msd

MS Sql Query problem mit not exists , help

Hello,

i hope that somebody can help me. I have a problem with ms sql query.

i have two tabels(wtmenSends and T1) in a database. i need pick up all email addresses from table wtmenSends but without those email addresses which are in table T1.

I have written this sql query to get these Emails, but i get nothing by this query. Can somebody tell me, where is the problem? Thanks.

select wtmenSends.Email

from

wtmenSends

where

notexists(

select

T1.*

from

(

SELECT

wtmenSends.Id, wtmenSends.Email, wtmenSends.IDMailing, wtmenSends.Title, wtmenSends.Firstname, wtmenSends.Lastname, wtmenSends.IDUser,

wtmenSends

.IdStatus, wtmenSends.IsSent, wtmenSends.DateSent, wtmenSends.wtobjIDClass, wtmenSends.wtobjDateCreated,

wtmenSends

.wtobjDateChanged, wtmenSends.wtobjUserCreated, wtmenSends.wtobjUserChanged

FROM

wtmenRobinsonsINNERJOIN

wtmenSends

ON wtmenSends.EmailNOTLIKE'%'+ wtmenRobinsons.FilterAND wtmenRobinsons.IsDomain= 1)as T1innerjoin

wtmenRobinsons

on wtmenRobinsons.Filter= T1.Email)

Hello my friend,

To start with, use the following SQL, and then add your extra clauses to it that you wish: -

SELECT Email FROM wtmenSends WHERE Email NOT IN

(SELECT Email FROM T1)

Kind regards

Scotty

|||

Hi Scotty,

thank you. my problem has been resolved.

best regards

pinsha

Monday, March 12, 2012

MS SQL Deadlock but no SQL transactions exists - Help

The deadlock victim occurred executing the line

DT3 = GetSQLTable("Select * from vw_RegsBeingMarked " & Where, cmd)
NotesDisplay is the .aspx page

You can clearly see that no transaction was in use, so the deadlock should not have occurred as far as I am concerned (3rd time I seen something like this).

This happened on MS SQL 2005 SP1.

The other part of this deadlock was caused by a delete statement (which did have a transaction) deleting rows that may have formed part of this view but that should only resulted in a normal lock, not a deadlock.

I have included the complete code that was executed along with the error message for reference.
Can anyone explain this?

PartialClass NotesDisplay

Inherits System.Web.UI.Page

Private mUserInfoAs Database.UserInfo

Private mDbAs Database

ProtectedSub Page_Load(ByVal senderAsObject,ByVal eAs System.EventArgs)HandlesMe.Load

Dim RegOccIDAsInteger =CInt(Request.QueryString(("RegOccID")))

Dim DT3As Data.DataTable

Main.GetSession(Me.Page, mUserInfo, mDb)

DT3 = mDb.MatchingRegs(RegOccID)

PublicFunction MatchingRegs(ByVal RegOccIDAsInteger)As DataTable

Dim DT3As Data.DataTable

DT3 = GetSQLTable("Select * from vw_RegsBeingMarked where RegOccID = " & RegOccID)

If DT3.Rows.Count = 0Then

ThrowNew Exception("Reg occ not found")

EndIf

Dim StartsAsDate

Dim EndsAsDate

Dim WhereAsString

With DT3.Rows(0)

Starts = .Item("Starts")

Ends = .Item("Ends")

If .Item("Ends")Is DBNull.Value =FalseAnd .Item("RoomID")Is DBNull.Value =FalseAnd .Item("RegStaff")Is DBNull.Value =FalseThen

' Posible merge with other regs

Dim cmdAsNew Data.SqlClient.SqlCommand

cmd.Parameters.AddWithValue("@.Starts", Starts)

cmd.Parameters.AddWithValue("@.Ends", Ends)

Where =" Where RoomID = " &CInt(.Item("RoomID")) &" AND Starts = @.Starts AND Ends = @.Ends AND RegStaff = " &CInt(.Item("RegStaff")) &" AND RoomID2 "

If .Item("RoomID2")Is DBNull.ValueThen

Where &=" is null"

Else

Where &=" = " &CInt(.Item("RoomID2"))

EndIf

DT3.Rows.Clear()

DT3 = GetSQLTable("Select * from vw_RegsBeingMarked " & Where, cmd)

EndIf

Return DT3

EndWith

EndFunction

PublicFunction GetSQLTable(ByVal SQLStringAsString,OptionalByRef CmdAs SqlCommand =Nothing)As DataTable

Dim myConnAs SqlConnection

Dim LocalConAsBoolean =False

If CmdIsNotNothingAndAlso Cmd.ConnectionIsNotNothingThen

myConn = Cmd.Connection

If SQLString =""Then

SQLString = Cmd.CommandText

EndIf

Else

myConn = DBOpenSQLConnection(SqlConEnum.Timetables)

LocalCon =True

EndIf

Try

GetSQLTable = GetSQLTableInternal(SQLString, myConn, Cmd)

Catch exAs Exception

Throw

Finally

If LocalConThen

DBCloseSQLConnection(myConn)

EndIf

EndTry

EndFunction

PrivateFunction GetSQLTableInternal(ByVal SQLStringAsString,ByRef myConnAs SqlConnection,OptionalByRef CmdAs SqlCommand =Nothing,OptionalByRef TransAs SqlTransaction =Nothing)As DataTable

Dim mySQLCommandAs SqlCommand

Dim mySQLAdaptorAs SqlDataAdapter

If CmdIsNothingThen

mySQLCommand =New SqlCommand

Else

mySQLCommand = Cmd

EndIf

mySQLCommand.Transaction = Trans

mySQLAdaptor =New SqlDataAdapter(mySQLCommand)

mySQLCommand.Connection = myConn

mySQLCommand.CommandText = SQLString

GetSQLTableInternal =New DataTable

mySQLAdaptor.Fill(GetSQLTableInternal)

EndFunction

Screen shot of SQL profiler deadlock information (showing lock types etc)
http://img299.imageshack.us/img299/9625/deadlockmb9.jpg

System.Data.SqlClient.SqlException: Transaction (Process ID 58) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)

at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)

at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)

at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)

at System.Data.SqlClient.SqlDataReader.HasMoreRows()

at System.Data.SqlClient.SqlDataReader.ReadInternal(Boolean setTimeout)

at System.Data.SqlClient.SqlDataReader.Read()

at System.Data.Common.DataAdapter.FillLoadDataRow(SchemaMapping mapping)

at System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue)

at System.Data.Common.DataAdapter.Fill(DataTable[] dataTables, IDataReader dataReader, Int32 startRecord, Int32 maxRecords)

at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)

at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)

at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)

at Database.GetSQLTableInternal(String SQLString, SqlConnection& myConn, SqlCommand& Cmd, SqlTransaction& Trans)

at Database.GetSQLTable(String SQLString, SqlCommand& Cmd)

at Database.MatchingRegs(Int32 RegOccID)

at NotesDisplay.Page_Load(Object sender, EventArgs e)

at System.Web.UI.Control.OnLoad(EventArgs e)

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

********************

at System.Web.UI.Page.HandleError(Exception e)

at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

at System.Web.UI.Page.ProcessRequest()

at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)

at System.Web.UI.Page.ProcessRequest(HttpContext context)

at ASP.notesdisplay_aspx.ProcessRequest(HttpContext context)

at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()

at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

The answer can be found here

http://groups.google.co.uk/group/microsoft.public.sqlserver.programming/browse_thread/thread/a05e7d7f4eabf61e/337c7c6d75c38452?lnk=st&q=ms+sql+server+2005+deadlock+no+transaction&rnum=25&hl=en#337c7c6d75c38452