How do I check if a table has contents? Honestly I still don't have any initial codes for it. Do I code it in VB or just use a query?
you definitely need to ask SQL server, so why not just querying 'SELECT COUNT(*) FROM TABLE" ?
which you can put it in a stored procedure.
even you can parametrise the procedure with table name and run exec sql command.
I would not use SELECT COUNT(*) unless you actually care about the actual count - this can be an expensive operation on large tables. If all you care about is whether there are rows or not, much better to use:
IF EXISTS (SELECT TOP (1) NULL FROM dbo.MyTable)
BEGIN
PRINT 'There are rows.';
END
ELSE
BEGIN
PRINT 'There are no rows.';
END
If you don't need to be up-to-the-second, you can use the DMVs for this kind of check. Specifically:
SELECT SUM(row_count)
FROM sys.dm_db_partition_stats
WHERE [object_id] = OBJECT_ID('dbo.MyTable');
The DMV is not always precise due to in-flight transactions and deferred updates, but is generally reliable for ballpark estimates.
Install Microsoft SQL Server Management Studio. You can then view the contents and structure of your tables, easily, through the GUI.
Dim con = New SqlConnection("Data Source=servername;Initial Catalog=myDb;Integrated Security=True")
Dim cmd = New SqlCommand("SELECT Count(*) FROM myTable", con)
con.Open()
Dim count As Integer = CInt(cmd.ExecuteScalar())
con.Close()
Related
I have the following code in a VB.net application that runs a stored procedure in MS Access. The stored procedure is an insert query based on the results of 2 other queries in the database.
When I run the Insert query manually within Access it runs fine and inserts the records as expected with no error or warnings. However, when I run using the ExecuteNonQuery() from my vb.net application I always get 0 back as the number of records inserted and it doesn't insert any records into the table. The code runs without errors. I have tested the code with other insert queries in the same db and it works fine so I know it's not the code or connection. It appears the problem has something to do with my query, but I can't figure out why it works in Access, but not from ExecuteNonQuery(). Sorry, but I can't post the exact query. I'm using VB.Net 2010 and MS Access 2013.
Please help!!!
Here is a generic version of my stored query:
INSERT INTO Table1 ( TESTID, Field1, Field2, Field3, DateImported )
SELECT DISTINCT Table2.Value1, Table2.Value2, Table2.Value3, Table2.Value4, Date() AS TodaysDate
FROM Table3 INNER JOIN Table2 ON Table3.TESTID = Table2.TESTID
I have tried it with and without the DISTINCT and I still have the same problem
Here is my code:
Dim conn As New OleDbConnection(MyConnectionString)
Try
Using conn
Using cmd As New OleDbCommand("My_Insert_Query", conn)
conn.Open()
cmd.CommandType = CommandType.StoredProcedure
NumRecordsAdded = cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
conn.Close()
End Try
I'm writing some Excel VBA for a user to be able to insert records into a SQL Server table, using ADODB. This is working fine:
Dim conn As New ADODB.connection
conn.Open "<my connection string>"
Dim records As New ADODB.Recordset
records.CursorLocation = adUseClient
records.Open "SELECT TOP 1 * FROM [MyTable]", conn, adOpenStatic, adLockBatchOptimistic, adCmdText
' (Add some stuff here.)
records.UpdateBatch
Something's nagging me, though: is it possible to get the recordset pointed at the right table without doing a SELECT up front? This could get to be a pretty big table, so SELECT * FROM [MyTable] is out. I'm limiting that with a TOP 1, but I'm only doing a write, so it feels like I shouldn't have to do that!
The documentation makes it sound like you can just put a table name in the Source argument:
Use the optional Source argument to specify a data source using one of the following: a Command object variable, an SQL statement, a stored procedure, a table name, [...]
In practice, this doesn't work for me, and all of the following just error out with the message below, like it thinks I'm calling a stored procedure:
records.Open "MyTable", conn, ' [...]
records.Open "[MyTable]", conn, ' [...]
records.Open "[dbo].[MyTable]", conn, ' [...]
The request for procedure 'MyTable' failed because 'MyTable' is a table object.
Is there some syntax I'm missing here, or do I just have to go with the SELECT?
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
I am writing a program in C# that runs some select statements using parameters passed to sp_executesql. One issue that I'm running into when testing is that, whether I get the the commands executed from SQL Profiler or from a watch in Visual Studio, the values of the parameters are specified at the end of statement rather than being explicitly specified in-line in the query. For testing purposes, I would like a quick way to substitute the parameter values for the parameters.
So, instead of:
exec sp_executesql N'
SELECT CustomerName
FROM CustomerTable ct WITH(NOLOCK)
WHERE ct.CustomerId <> #CustomerId
AND ct.ItemId <> #ItemId
AND ct.TransactionId = #TransactionId'
,N'#CustomerId bigint,#ItemId nvarchar(1),#TransactionId nvarchar(30), #CustomerId = 3000, #ItemId = N'4', #TransactionId=N'43281'
I want:
exec sp_executesql N'
SELECT CustomerName
FROM CustomerTable ct WITH(NOLOCK)
WHERE ct.CustomerId = 3000
AND ct.ItemId <> N'4'
AND ct.TransactionId = N'43281''
Please don't pay too much attention to the syntax of the example, since it is just being used to demonstrate the concept. Does anyone know a fast way to do this? Basically, I would like to have it substituted for testing purposes, as it will make it easier for me to modify conditions to test how they affect the results returned. I would appreciate any help anyone can give. Thanks.
Parameterized sp_executesql has many benefits, including
By explicit parameterizing you are giving the chance for SQL to cache decent query plans on definite types
By parameterizing it helps prevent nasties like SQL injection attacks, but also avoids the need to escape problematic characters.
So even if you do manage to 'unparameterize' the generated sp_executesql, if you execute the inline sql, the query plan could be significantly different to the parameterized version, and you would also need to do escaping etc (i.e. it wouldn't be suitable for apples vs apples testing).
The only reason I can think of why you wouldn't want parameterized sp_executesql would be for ease of readability?
Edit: Trying to substitute would be dependent on what technology you are using
As #mellamokb suggested, if you are using ExecuteReader this could be quite straightforward
Assuming your code was something like
string sqlCmd = "SELECT CustomerName
FROM CustomerTable ct WITH(NOLOCK)
WHERE ct.CustomerId <> #CustomerId
AND ct.ItemId <> #ItemId
AND ct.TransactionId = #TransactionId";
cmd.CommandText = sqlCmd;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("CustomerId", DbType.Int32, myCustomerId));
cmd.Parameters.Add(new SqlParameter("ItemId", DbType.String, myItemId));
..
cmd.ExecuteReader()
You could then add code to build your test query:
string sqlMyTest = sqlCmd.Replace("#CustomerId", myCustomerId.ToString());
sqlMyTest = sqlMyTest.Replace("#ItemId", specialEscapeFunction(myItemId));
.. do something with sqlMyTest
However an ORM like Linq2SQL or EF would not be as easy
customerTable.Where(c => (c.CustomerId != myCustomerId) && (c.ItemId != myItemId) && (c.TransactionId == myTransactionId))
Possibly a tool like LinqPad might help?
I have 2 databases. In first one I have 10 tables. Second one is only 1 table. I would like to select 1 columns from each table from 1st database and Insert INTO another database. How can I manage this using INSERT INTO statement in VB.net?
I deleted my previous answer saying that you have to manually copy over the data. For now, let's assume you want to do this with a SELECT INTO statement.
The following code shows you how to execute a SQL command on your database using a ADO.NET connection and command object:
' Open a connection to your database (e.g. in a SQL Server): '
Using connection As IDbConnection = New SqlConnection("<Connection string>")
connection.Open()
Try
' Define the SQL command to be executed here: '
Dim command As IDbCommand = connection.CreateCommand()
command.CommandText = "SELECT <...> INTO <...>"
' Execute the command: '
command.ExecuteNonQuery()
Finally
connection.Close()
End Try
End Using
I hope this helps:
From sql side, you'll just need to write a stored procedure to insert into (ten) hash tables and select/insert them into your target table.
In Vb.net, you'll need: a connection object and a command object to call your stored procedure