select from access database file and insert to sql Database - sql

I have an access database file (test.mdb) and I need to write a stored procedure which will select some records from tblTest in test.mdb and insert them into tbsqlTest in my sql database .
==> I need a SP like this :
BEGIN
select * into tblTest from [test.mdb].[tblTest]
where (my condition)
END

If you're willing to permit Ad Hoc Distributed Queries on your SQL Server, you could use OPENDATASOURCE to retrieve data from an MDB file.
SELECT * INTO dbo.TestAccess FROM OPENDATASOURCE(
'Microsoft.Jet.OLEDB.4.0',
'Data Source="\\server\share\somefolder\scratchpad.mdb"')...MyTable;
Or after creating the destination table, you might prefer:
INSERT INTO dbo.TestAccess
SELECT * FROM OPENDATASOURCE(
'Microsoft.Jet.OLEDB.4.0',
'Data Source="\\server\share\somefolder\scratchpad.mdb"')...MyTable;
In order to get those to run, I had to enable Ad Hoc Distributed Queries like this:
sp_configure 'show advanced options', 1;
RECONFIGURE WITH OVERRIDE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE WITH OVERRIDE;
GO
I found configuration instructions on TechNet, but it didn't work for me until I added WITH OVERRIDE.
Edit: I added a sql-server tag to your question because I want to find out whether my suggestion is foolishly risky. Perhaps setting up the MDB as a linked server is a safer way to go here. I don't know.

If you are going to be doing this regularly;
Create an append query in design view that does what you want it to do, including the criteria by which to filter the query results.
View the query in SQL view.
Copy the SQL Text
Create a button on your form. Go to the properties window, under the event tab, and select the "on click" event. Click the ellipsis "..." and open the code.
Use this code:
Dim MyAppendString as String
MyAppendString = " (Code line 1) " & _
" (Code line 2) " & _
" (Last line) ";
docmd.runsql MyAppendString
Every time you click the button, it will execute the append query, hardcoded with the criteria you selected.
Let me know if you stick on any of these points. I'll send you more detailed instructions.

Related

Running a Stored Proc via Excel Connection - works in SSMS but not via the VBA macro

I've successfully created many connections in an Excel file to a Database so the issue is directly related only to this particular scenario. Server is 2012, Excel is 2013.
I have the following SP:
IF OBJECT_ID('usp_LockUnlockCustomer', 'P') IS NOT NULL
DROP PROCEDURE usp_LockUnlockCustomer
GO
CREATE PROCEDURE usp_LockUnlockCustomer
#Lock AS CHAR(10), #Id AS nvarchar(50), #LockedBy AS nvarchar(50)=null
AS BEGIN
SET NOCOUNT ON;
IF #Lock = 'Lock'
INSERT INTO IO_Call_DB..IdLock (Id, LockedBy, LockedDtTm)
VALUES(#Id,#LockedBy,GETDATE())
;
IF #Lock = 'Unlock'
DELETE FROM IO_Call_DB..IdLock
WHERE Id = #Id
;
END;
--EXEC usp_LockUnlockCustomer 'Lock','123456789', 'Test User'
The above SP is called via some VBA as follows:
With ActiveWorkbook.Connections("usp_LockUnlockCustomer").OLEDBConnection
.CommandText = "EXECUTE dbo.usp_LockUnlockCustomer '" & bLock & "','" & Id & "','" & LockedBy & "'"
End With
I have tested the string and the string is formatted correct & contains all required data.
The connection between Excel and SQL is created via "Data > From Other Sources > From SQL Server", it's a fairly standard process which has worked for all other SP's and general queries.
I think, because this connection is not returning data to Excel (I only set up the connection rather than specifying that Excel should return data to a cell) that this may be the issue.
Has anyone experienced this issue before?
EDIT1: I have resolved the issue but it's not a particularly great outcome. Some help would be appreciated.
To resolve the issue, you have to include a "select * from" process at the end of the stored procedure and also tell Excel to output the data to a range within the workbook. This allows the .Refresh portion of the VBA to do whatever it does & submit the SP to SQL.
Essentially, you're being forced to create a data table - but I don't want any data, I just want to submit a command.
So, how do you submit a command and not have Excel require that you 1) explicitly state where the data should be put 2) include a SELECT statement within the stored procedure when I don't require any data to be returned.
My fix was to "select top 0" from the table, at least that way the data table being output to Excel won't grow.
In my experience if you generate the database connection in VBA, (there are multiple previous questions about that), rather than rely on an existing workbook connection, your stored procedure will execute regardless of what it returns.
The problem I have is that by merely creating the connection without specifying a cell to return data to, nothing happens.
In addition, if I specify a cell to return data to, nothing happens unless I use my 'fix' which is to create an empty table at the end of the SP.

How to copy table from Production to Development?

I am working on Development Server Named as SQLDEV01 and the db name is University and the table name is cse.students. During my work on table cse.students I lost some rows so I need to get the all the exact data from Production server.production Server Name is SQLPROD01.
How can I query to get the production data without using SSIS?
Setup a linked server from the development to production servers before doing the following from SSMS. All code should be executed on the development server.
http://technet.microsoft.com/en-us/library/ms188279.aspx
-- On Development server [SQLDEV01]
TRUNCATE TABLE [University].[cse].[students];
GO
-- Use link server to move data
INSERT INTO
[University].[cse].[students]
SELECT
*
FROM
[SQLPROD01].[University].[cse].[students]
GO
This assumes there are no identity columns on the target.
If you do have identity columns, turn on/off allow inserts before/after executing the above insert.
-- Before Insert, execute this statement
SET IDENTITY_INSERT [University].[cse].[students] ON
GO
-- After Insert, execute this statement
SET IDENTITY_INSERT [University].[cse].[students] OFF
GO
You can also create an ad-hoc connection using the OPENROWSET command.
http://technet.microsoft.com/en-us/library/ms190312.aspx
INSERT INTO
[University].[cse].[students]
SELECT
PRD.*
FROM
OPENROWSET('SQLNCLI', 'Server=SQLPROD01;Trusted_Connection=yes;',
'SELECT * FROM [University].[cse].[students]') AS PRD;
I did not check the syntax for your environment, please check.
If add hoc queries are set off (0), have the DBA turn them on (1) temporarily. Execute the following on the production server.
http://msdn.microsoft.com/en-us/library/ms187569.aspx
-- Show all settings
sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
-- What is the current setting?
sp_configure
GO
-- Allow add hoc queries
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
If (s)he does not allow that, you are stuck with a physical linked server.
If you are using delegation - choice #3, you have to watch out for the double hop issue.
http://blogs.msdn.com/b/sql_protocols/archive/2006/08/10/694657.aspx
I would configure the linked server with a specific account on production that has rights to select the data. See choice #4.
There are a few ways to do this. One that is pretty much failsafe is the following:
In Microsoft SQL Management Studio expand the server node for the source server - Then expand the Databases node. Right click on the source database and select Tasks -> Generate Scripts. When the dialog pops up click next. Select the "Select specific database objects" radio button. Expand the Tables node as check the table you want to copy. Click the next button at the bottom. Click the advanced button. In the options that pop up for Script DROP and CREATE select Script DROP and CREATE on the right. For the option Type of data to script select schema and data on the right. Click OK. Now back on the main dialog you need to select "Save to Clipboard" or "Save to new query window". I usually select clipboard because I am usually going to a different server but select what works best for you. Click next. Click next again and the script will generate according to your selections. Now just run that script on the destination database.
please use this query generalized query by replacing your entries
select * into targetTable from [sourceserver].[sourcedatabase].[dbo].[sourceTable]

Read contents of a text file into a varchar WITHOUT using BULK

I've got a problem whereby I need to read data from a .txt file into a variable in SQL Server. The read needs to be performed programmatically, as it's going to form part of a stored procedure, and it needs not to utilise the BULK method, as I don't have permissions to use the BULK method on the database in question. Is this possible?
Thanks in advance :)
Can you get them to allow Ad Hoc Distributed Queries? Then you can use OpenRowset or OpenDatasource.
SELECT *
FROM OPENROWSET('MSDASQL',
'Driver={Microsoft Text Driver (*.txt; *.csv)};DefaultDir=c:\users\graham\desktop;',
'SELECT * FROM [data.txt];'
Here's the recofiguring code, if you need it:
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
go
This is a laborious technique, though -- you sure you can't use client code? Even, I dunno, VBA in Excel or something?
g.
There is no other way to read the contents of a file without these permissions in SQL Server, or without setting up a link to the file. Otherwise, you have to do this through SSIS or using programming.
The solution is to get the permissions to solve your issue.

Opening a batch file using SQL Server procedure

Opening a batch file using SQL Server procedure....
For this, I took the example of opening a notepad. And able to open it with the following code :
start "c:\windows\system32" notepad.exe
--- saved as : note.bat
I tried to open it with following procedure :
ALTER procedure [dbo].[executebat]
as
begin
EXEC master.dbo.xp_CMDShell 'D:\ducont\note.bat'
end
also I enabled the xp_cmdshell option with following code ::
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO
But when I try to execute the procedure, it showing continuously
" Query Executing..."
and no output !!
Guide me if I went wrong anywhere .
Simple answer. When you run xp_cmdshell it is creating a shell to do any work you ask it to. Your bat file is running inside that shell, and will open notepad, again inside the shell. You just won't be able to see it. Since it's expecting input (and can't get any) you are stuck with the " Query Executing..."
There really isn't a good way to do what you are asking for other than possibly using CLR. Unfortunately I don't know enough about it to say for certain one way or another. There may be an easier way in SQL 2012 or 2014 but I haven't seen it yet.

I need best practice in T-SQL Export data to CSV (with header)

What I need to do is export data into CSV file using T-SQL.
And I'm very confused about there are many ways can do it, I don't know to choose which one, please help me to confirm the bollowing:
As I know there are about 3 methods, and I want you help me to confirm:
Using Microsoft.Jet.OLEDB.4.0, like this:
INSERT INTO OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Text;Database=C:\Temp\;HDR=Yes;',
'SELECT * FROM test.csv')
(object_id, name)
SELECT object_id, name
FROM sys.tables;
but this need the csv file is there, and with header
using SQLCMD
command line.
using BCP
Use union, get data and it's column header.
This is all my understanding about T-SQL export to CSV, please help me to confirm.
Is there other way to export to CSV?
Thanks!
Execute the below command in SQL Server:
EXEC xp_cmdshell 'SQLCMD -S . -d MsVehicleReg2 -Q "SELECT * FROM tempViolationInfo" -s "," -o "O:\result.csv"';
You could use a UNION to create a header row, like this:
SELECT 'object_id', 'name'
UNION ALL
SELECT object_id, name
FROM sys.tables
Here is the T-SQL way:
INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Text;Database=D:\;HDR=YES;FMT=Delimited','SELECT * FROM [FileName.csv]')
SELECT Field1, Field2, Field3 FROM DatabaseName
But, there's a couple of caveats:
You need to have the Microsoft.ACE.OLEDB.12.0 provider available. The Jet 4.0 provider will work, too, but it's ancient, so I used this one instead.
The .CSV file will have to exist already. If you're using headers (HDR=YES), make sure the first line of the .CSV file is a delimited list of all the fields.
For Ace.OLEDB.12.0 (the new Jet redistributable engine), you can install the 32-bit or 64-bit stand-alone engine, even if you have the "other flavor" already installed, whether on its own, from Access, etc:
use the /passive command-line option:
(32-bit): AccessDatabaseEngine.exe /passive
(64-bit): AccessDatabaseEngine_64.exe /passive
In my case, I have 64-bit SQL Express 2008 R2, and had 32-bit Office 12 apps installed (thus, the 32-bit ACE drivers were installed). I installed the 64-bit AccessDatabaseEngine_64.exe, and it's sort of working for me now...
Also, this is assuming you've done the other configuration work:
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0',
N'AllowInProcess', 1
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0',
N'DynamicParameters', 1
GO
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
regarding "best practice", there is no best practice.
there are several options available, not limited to:
in T-SQL with INSERT INTO OPENROWSET(...) SELECT * from [MyTable]...
executing BCP, whether from a job step or in T-SQL with xp_cmdshell
SSIS packages
PowerShell (from a job step, in SQL Server 2008+) or other external script/executable