List all triggers in a database - vb.net

Is it possible to list all triggers in all tables on a database?
I can list all user stored procedures with:
Private Sub StoredPro()
Dim theServer As Server = New Server(serverName)
Dim myDB As Database = theServer.Databases("mydatabase")
Dim dt As DataTable = myDB.EnumObjects(DatabaseObjectTypes.StoredProcedure)
End Sub
But nothing obvious in SMO for triggers. (I'm actually trying to list just custom triggers, any that are not named DEL_tablename, INS_tablename, UPD_tablename) within the selected database.

https://social.msdn.microsoft.com/forums/sqlserver/en-US/bb024fd6-c0b9-441a-864e-a579fc441267/list-databasetable-triggers-via-smo
A DatabaseDdlTrigger object represents a data definition language (DDL) trigger, which is created on a SQL Server database. However, from your description, I think you want to iterate over the data manipulation language (DML) triggers, which are created on SQL Server tables.
Please refer to the following sample:
Dim srv As New Server
Dim db As Database = srv.Databases.Item("Northwind")
Dim tb As Table
For Each tb In db.Tables
Dim trg As Trigger
For Each trg In tb.Triggers
If (((trg.Name <> ("INS_" & tb.Name)) AndAlso (trg.Name <> ("DEL_" & tb.Name))) AndAlso (trg.Name <> ("UPD_" & tb.Name))) Then
MessageBox.Show(trg.Name)
End If
Next
Next

Each database object has a Triggers property, which you can iterate to find all triggers.
Once you have a reference to this trigger, check the IsSystemObject property to check if it is a user-defined trigger or not.
foreach ( DatabaseDdlTrigger oTrigger in oDatabase.Triggers) {
if (! oTrigger.IsSystemObject) {
// do something
}}
Have fun.

Related

How to store server auto generated value to Primary key column

I was working on an application that uses sql server database. I the auto generated value for the primary key to be stored into dataset. I was using the below code. But the problem is my primary key column ie, ProdNum is readonly. For that it won't allow to set that value. How can I overcome this?
Private Sub OnRowUpdated(ByVal sender As Object, ByVal args As Data.OleDb.OleDbRowUpdatedEventArgs)
' Include a variable and a command to retrieve the identity value from the Access database.
Dim newID As Integer = 0
Dim idCMD As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT ##IDENTITY", args.Command.Connection(), args.Command.Transaction)
If args.StatementType = StatementType.Insert Then
' Retrieve the identity value and store it in the ProductIDNum column.
newID = CInt(idCMD.ExecuteScalar())
' place in the identity column of the local table in the dataset
'args.Row("ProdNum") = newID
End If
End Sub
I'm not sure whether you can do this using OleDb (you can't for Access, but that's a different OLE DB provider) but if you use SqlClient then there's no need to handle any events because you can simply tack a SELECTonto your INSERT in the CommandText of your adapter's InsertCommand, e.g.
INSERT INTO Thing (Name, Description) VALUES (#Name, #Description);
SELECT ThingId = SCOPE_IDENTITY();
That's always worked for me.

MS-Access Database Locking when running a Insert Query via VBA

I am creating a simple database. I have a functionality where i have simply created a Insert Into query an saved it in the database. what i want to do is,
call that query in VBA code.
I have done following coding :
Private Sub Update_ISO_Review_Register()
Dim dbs As DAO.Database
Set dbs = CurrentDb
dbs.Execute "Update_ISO_Review_Register_ApplicationData"
dbs.Close
Set dbs = Nothing
End Sub
The code works and it executes the query. Issue is that after that it locks the database and it gives the following error.
You do not have exclusive access to the database at this time. if you
proceed to make changes, you may not be able to save them later.
The SQL for the Update_ISO_Review_Register_ApplicationData query is:
INSERT INTO ISO_REVIEW_REGISTER ( SLTF_Ref, Brand, Application_No )
SELECT DISTINCT b.matter_No AS SLTF_Ref
, b.Brand
, b.CREDIT_APPLICATION_ID AS Application_No
FROM WBC_HFM_FileReveiw_Table AS a INNER JOIN WBC_HFM_Application_Table AS b ON
a.CREDIT_APPLICATION_ID = b.CREDIT_APPLICATION_ID;
Any help ?
Would it work if you only do this:
Private Sub Update_ISO_Review_Register()
CurrentDb.Execute "Update_ISO_Review_Register_ApplicationData"
End Sub
You can nicely live without these:
Dim dbs As DAO.Database
Set dbs = CurrentDb
dbs.Close
Set dbs = Nothing
especially set set dbs = Nothing, which is a local variable and "dies" after End Sub.

How to check if a database and tables exist in sql server in a vb .net project?

Can anyone tell me how I would go about checking if a database and tables exists in sql server from a vb.net project? What I want to do is check if a database exists (preferably in an 'If' statement, unless someone has a better way of doing it) and if it does exist I do one thing and if it doesn't exist I create the database with the tables and columns. Any help on this matter would be greatly appreciated.
Edit:
The application has a connection to a server. When the application runs on a PC I want it to check that a database exists, if one exists then it goes and does what it's supposed to do, but if a database does NOT exist then it creates the database first and then goes on to do what it's supposed to do. So basically I want it to create the database the first time it runs on a PC and then go about it's business, then each time it runs on the PC after that I want it to see that the database exists and then go about it's business. The reason I want it like this is because this application will be on more than one PC, I only want the database and tables created once, (the first time it runs on a PC) and then when it runs on a different PC, it sees that the database already exists and then run the application using the existing database created on the other PC.
You can query SQL Server to check for the existence of objects.
To check for database existence you can use this query:
SELECT * FROM master.dbo.sysdatabases WHERE name = 'YourDatabase'
To check for table existence you can use this query against your target database:
SELECT * FROM sys.tables WHERE name = 'YourTable' AND type = 'U'
This below link shows you how to check for database existence is SQL Server using VB.NET code:
Check if SQL Database Exists on a Server with vb.net
Referenced code from above link:
Public Shared Function CheckDatabaseExists(ByVal server As String, _
ByVal database As String) As Boolean
Dim connString As String = ("Data Source=" _
+ (server + ";Initial Catalog=master;Integrated Security=True;"))
Dim cmdText As String = _
("select * from master.dbo.sysdatabases where name=\’" + (database + "\’"))
Dim bRet As Boolean = false
Using sqlConnection As SqlConnection = New SqlConnection(connString)
sqlConnection.Open
Using sqlCmd As SqlCommand = New SqlCommand(cmdText, sqlConnection)
Using reader As SqlDataReader = sqlCmd.ExecuteReader
bRet = reader.HasRows
End Using
End Using
End Using
Return bRet
End Function
You could perform the check in another way, so it's done in a single call by using an EXISTS check for both the database and a table:
IF NOT EXISTS (SELECT * FROM master.dbo.sysdatabases WHERE name = 'YourDatabase')
BEGIN
-- Database creation SQL goes here and is only called if it doesn't exist
END
-- You know at this point the database exists, so check if table exists
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'YourTable' AND type = 'U')
BEGIN
-- Table creation SQL goes here and is only called if it doesn't exist
END
By calling the above code once with parameters for database and table name, you will know that both exist.
Connect to the master database and select
SELECT 1 FROM master..sysdatabases WHERE name = 'yourDB'
and then on the database
SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'yourTable'
i dont know the exact vb syntax but you only have to check the recordcount on the result
For tables and other objects inside a database, I usually do it this way but it's really personal preference.
IF OBJECT_ID('dbo.blah') IS NOT NULL
BEGIN
END
For VB.NET, I'd wrap this in a stored procedure and call that. I'm sure there are also ways to do this with Linq.
You can use This query for check database
IF DB_Id('YourDatabaseName') IS NOT NULL
BEGIN
PRINT 'DB EXISTS'
END
ELSE
BEGIN
PRINT 'DB NOT EXISTS'
END
Friend Function CheckDatabaseExists(server As String, database As String) As Boolean
Dim connString As String = "Data Source=" + server + ";Initial Catalog=master;Integrated Security=SSPI"
Dim cmdText As String = "select * from master.dbo.sysdatabases where name='" + database + "'"
Dim bRet As Boolean = False
Using sqlConnection As SqlConnection = New SqlConnection(connString)
sqlConnection.Open
Using sqlCmd As SqlCommand = New SqlCommand(cmdText, sqlConnection)
Using reader As SqlDataReader = sqlCmd.ExecuteReader
bRet = reader.HasRows
End Using
End Using
End Using
Return bRet
End Function
Public Function SQLDatabaseExist(ByVal DefaultConnectionString As String, ByVal DataBaseName As String) As Boolean
Try
'CREATE DATABASE
Dim SqlString As String = ""
SqlString = "SELECT CASE WHEN EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'" & DataBaseName & "') THEN CAST (1 AS BIT) ELSE CAST (0 AS BIT) END"
Dim ExcRet As Integer = 0
Using connection As New SqlConnection(DefaultConnectionString)
Dim command As New SqlCommand(SqlString, connection)
command.Connection.Open()
ExcRet = command.ExecuteScalar()
command.Connection.Close()
command.Dispose()
End Using
Return ExcRet
Catch ex As Exception
Return False
End Try
End Function

Insert X rows into child table based on parent field

Trying to insert a set number of rows into a child table based on a number entered into a parent table
parent (licenseID, poolSize)
child (nodeID, licenseID)
I was looking into using an After Insert trigger on the parent table but could not figure out how to loop a create record command.
Is this possible to do with macros or should I be looking at VBA code? (MS ACCESS 2010)
First of all, I would never enter anything directly into a table. Giving your users that kind of ability is always going to end up in some form of misery and regret.
I would creat a form to take the number, and then use code behind a "Submit" button to loop the required number of times. Something like (this code is entirely untested):
Dim db as Database
Dim rec as Recordset
Dim X as Double
Set db = CurrentDB
Set rec = db.OpenRecordset ("Child")
Do for X = 1 to Me.txtNumberOfEntries
rec.AddNew
rec("LicenseID") = me.txtLicenseID
rec.Update
Next X
'Always clear out your variables
Set rec = Nothing
Set db = Nothing

How to check table exist or not exist

How to check table is there or not?
Using VB 6.0
cmd.CommandText = "drop table t1"
cmd.Execute
Above code is working fine, but if table is not exist then it showing “table does not exit”
How to check table exist or table not exist?
Need VB CODE help?
If you just want to drop the table without throwing an error message, you can use the following SQL if you're using MySQL.
DROP TABLE t1 IF EXISTS
Other databases have a similar feature, but the syntax is different. To do the same in MSSQL:
IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 't1') DROP TABLE t1;
Although that looks very ugly.. there must be a better syntax to get the same result.
For a Jet MDB (and perhaps generically for many OLEDB Providers) you can use an approach like:
Private Sub Main()
Dim cnDB As ADODB.Connection
Set cnDB = New ADODB.Connection
cnDB.Open "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Jet OLEDB:Engine Type=5;Data Source='sample.mdb'"
'Check presence of table --------------
Dim rsSchema As ADODB.Recordset
Set rsSchema = _
cnDB.OpenSchema(adSchemaColumns, _
Array(Empty, Empty, "t1", Empty))
If rsSchema.BOF And rsSchema.EOF Then
MsgBox "Table does not exist"
Else
MsgBox "Table exists"
End If
rsSchema.Close
Set rsSchema = Nothing
'--------------------------------------
cnDB.Close
End Sub
You'd be better off checking for existence of the table concerned, rather than trying to drop it.
The SQL syntax is dependent on the database server/engine you're using, but for Sql Server you could use something like:
Sql Server 2000:
SELECT 1 as Exists FROM sysobjects WHERE name = 't1'
Sql Server 2005/2008:
SELECT 1 as Exists FROM sys.objects WHERE name = 't1'
You can then use VB like:
Dim rs as Recordset
Dim iExists as Integer
rs = cmd.Execute
On Error Goto DoesNotExist
rs.MoveFirst
iExists = CInt(rs!Exists)
DoesNotExist:
If iExists = 1 Then
' Put code here for if the table exists
Else
' Put code here for if the table does not exist
End If
Note: This code needs tidying up and "productionising" (i.e. I haven't actually tested that it works as I don't have VB6 on this machine)