Pogrammatically Change The Database Location - sql-server

Im making a program with visual basic 2010 and using sqlserver compact as database. I have two folders named "Year2015" and "Year2016". The folders are in the same location where the program is. Both folders has a database named "MyData.sdf" in themselves. Both of the "MyData.sdf" has the same tables etc. Im trying to do something like that:
When user select "Year2015", program starts to run with the data of "MyData.sdf" that is in the folder "Year2015" and when user select "Year2016", program starts to run with the data of "MyData.sdf" that is in the folder "Year2016". I mean that i want to change the datasource address programmaticly. Searched net for that. There are some explanations but no codes i could find. If this is a bad question sorry for that.

Dave Pinal is a genius at this stuff, and I happened to read his blog on this very topic:
ALTER DATABASE TestDB
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
GO
-- Detach DB
EXEC MASTER.dbo.sp_detach_db #dbname = N'TestDB'
GO
-- Move MDF File from Loc1 to Loc 2
-- Re-Attached DB
CREATE DATABASE [TestDB] ON
( FILENAME = N'F:\loc2\TestDB.mdf' ),
( FILENAME = N'F:\loc2\TestDB_log.ldf' )
FOR ATTACH
GO
Note: even his comment sections are great, too!
*SOURCE SCRIPT CAME FROM PINAL.
http://blog.sqlauthority.com/2012/10/28/sql-server-move-database-files-mdf-and-ldf-to-another-location/

I finally create my own code for this issue. I want to share it for the people who uses VB2010 and SQL Server Compact and want to change the data source for the active form. The code is:
Dim sConnectionString As String
sConnectionString = "Data Source=" & My.Computer.FileSystem.CurrentDirectory & "\Year2015\MyData.sdf"
TableAdapterManager.Connection.ConnectionString = sConnectionString
This will change your data source of active form. The other forms continues to use the default source

Related

Why the path of my file is not correct when I trying to create database?

I just started learning SQL. I downloaded the mdf file and moved it to the SQL folder. The course instructor told us to enter these commands to display the finished database. It throws me the error that my file doesn't exist even though I entered the correct path name. What is the matter? Sorry if the question is too stupid I just started learning.
Here is some pictures of the problem.
Your .mdf file should be in this path:
FILENAME = N'C:\MSSQL\SQLData\<database name>.mdf'
To attach a database there are some ways to do it like :
The one i've showed you:
USE [master]
GO
create database <DatabaseName> ON
(name='LogicalName of the Data file', FileName='Data File Name'),
(name='LogicalName of the Log file', FileName='Log File Name')
FOR ATTACH;
Or this way:
USE [master]
GO
EXEC sp_attach_db #dbname = N'DatabaseName',
#filename1 = '<Location of the database file>',
#filename2 = '<Location of the Log file>';

Delphi TFDTable open fails when indexname is set

Using Delphi 10.3.3, mainly under Windows10, I have a number of [FireDAC] TFDTable components accessing an SQL Server DB.
Everything worked fine in delphi 10.2.3 but in the Rio version, I find that those TFDtables which have an indexname set and which access a DB whose name has a space in it, fail with the message "[FireDAC]{DatS]-2 Object [PK_DEPT] is not found."
An example of the table definition in the dfm is:
object tbHODEPT: TFDTable
IndexName = 'PK_DEPT'
ConnectionName = 'HEADOFFICE'
FetchOptions.AssignedValues = [evMode]
FetchOptions.Mode = fmAll
UpdateOptions.UpdateTableName = 'DEPT'
TableName = 'DEPT'
The connection, "HEADOFFICE", is a TFDConnection descendant which just adds the credentials for the relevant DB at open-time. I have noticed that if I supply a fully qualified TableName property (e.g. '[Some DBname].dbo.[DEPT') then the problem does not occur. But setting the DBname at design time is undesirable as we allow the DB names to be configurable.
Barring a solution, my options seem to be
Renaming the problematic DB, and
Changing all of the affected TFDTables to use indexfieldnames instead. (This works OK).
Ideas welcome.

Optionally including scripts in SQL Server Projects 2012

I am building a SQL Publish Script that will be used to generate a database to our internal servers, and then used externally by our client.
The problem I have is that our internal script will automate quite a few things for us, in which the actual production environment will require these completed manually.
For example, internally we would use the following script
-- Global variables
:setvar EnvironmentName 'Local'
-- Script.PostDeployment.sql
:r .\PopulateDefaultValues.sql
IF ($(EnvironmentName) = 'Test')
BEGIN
:r .\GivePermissionsToDevelopmentTeam.sql
:r .\PopulateTestData.sql
:r .\RunETL.sql
END
ELSE IF ($(EnvironmentName) = 'Client_Dev')
BEGIN
:r .\GivePermissionsToDevWebsite.sql
END
This would generate a script like this:
-- (Ignore syntax correctness, its just the process I'm after)
IF($(EnvironmentName) = 'Test')
BEGIN
CREATE LOGIN [Developer1] AS USER [MyDomain\Developer1] WITH DEFAULT SCHEMA=[dbo];
CREATE LOGIN [Developer2] AS USER [MyDomain\Developer2] WITH DEFAULT SCHEMA=[dbo];
CREATE LOGIN [Developer3] AS USER [MyDomain\Developer3] WITH DEFAULT SCHEMA=[dbo];
-- Populate entire database (10000's of rows over 100 tables)
INSERT INTO Products ( Name, Description, Price ) VALUES
( 'Cheese Balls', 'Cheesy Balls ... mm mm mmmm', 1.00),
( 'Cheese Balls +', 'Cheesy Balls with a caffeine kick', 2.00),
( 'Cheese Squares', 'Cheesy squares with a hint of ginger', 2.50);
EXEC spRunETL 'AUTO-DEPLOY';
END
ELSE IF($(EnvironmentName) = 'Client_Dev')
BEGIN
CREATE LOGIN [WebLogin] AS USER [FABRIKAM\AppPoolUser];
END
END IF
This works fine, for us. When this script is taken on site, the script fails because it cannot authenticate the users of our internal environment.
One item I thought about permissions was to just give our internal team sysadmin privileges, but the test data just fills the script up. When going on site, having all of this test data just bloats the published script and isn't used anyway.
Is there any way to exclude a section entirely from a published file, so that all of the test data and extraeous inserts are removed, without any manual intervention of the published file?
Unfortunately, there is currently no way to remove the contents of a referenced script from the generated file entirely.
The only way to achieve this is to post-process the generated script (Powershell/Ruby/scripting language of choice) to find and remove the parts you care about using some form of string and file manipulation.
Based on: My experience with doing this exact same thing to remove a development-environment-only script which was sizable and bloated the Production deployment script with a lot of 'noise', making it harder for DBA's to review the script sensibly.

Oracle external tables - Specifying dynamic filename

CREATE TABLE LOG_FILES (
LOG_DTM VARCHAR(18),
LOG_TXT VARCHAR(300)
)
ORGANIZATION EXTERNAL(
TYPE ORACLE_LOADER
DEFAULT DIRECTORY LOG_DIR
ACCESS PARAMETERS(
RECORDS DELIMITED BY NEWLINE
FIELDS(
LOG_DTM position(1:18),
LOG_TXT position(19:300)
)
)
LOCATION('logadm'))
)
REJECT LIMIT UNLIMITED
/
LOG_DIR is an oracle directory that points to /u/logs/
The problem though is that the contents of /u/logs/ looks like this
logadm_12012012.log
logadm_13012012.log
logadm_14012012.log
logadm_15012012.log
Is there any way i can specify the location of the file dynamically? i.e. every time i run Select * from LOG_FILES it should use the log file of the day. (e.g. log_adm_DDMMYYYYY).
I know i can use alter table log_files location ('logadm_15012012.log') but i would like not to have to issue the alter command.
Any other possibilities?
Thanks
It's a shame you're running 10g. On 11g we can associate a pre-processor script - a shell script - with an external table. In your case you could run a script which would figure out the latest file and then issue a copy command. Something like:
cp logadm_15012012.log logadm
Adrian Billington has blogged about this feature here. Frankly his write-up is more helpful than the official docs.
But as you're on 10g all you can do is run the ALTER TABLE statement, or use a scheduled job (cron or whatever) to sync a new file with the generic name.

PowerBuilder DSN Creation

I am new to PowerBuilder.
I want to retrieve the data from MSAccess tables and update it to corresponding SQL tables. I am not able to create a permanent DSN for MSAccess because I have to select different MSAccess files with same table information. I can create a permanent DSN for SQL server.
Please help me to create DSN dynamically when selecting the MSAccess file and push all the tables data to SQL using PowerBuilder.
Also give the full PowerBuilder code to complete the problem if its possible.
In Access we strongly suggest not using DSNs at all as it is one less thing for someone to have to configure and one less thing for the users to screw up. Using DSN-Less Connections You should see if PowerBuilder has a similar option.
Create the DSN manually in the ODBC administrator
Locate the entry in the registry
Export the registry syntax into a .reg file
Read and edit the .reg file dynamically in PB
Write it back to the registry using PB's RegistrySet ( key, valuename, valuetype, value )
Once you've got your DSN set up, there are many options to push data from one database to the other.
You'll need two transaction objects in PB, each pointing to its own database. Then, you could use a Data Pipeline object to manage the actual data transfer.
You want to do the DSNLess connection referenced by Tony. I show an example of doing it at PBDJ and have a code sample over at Sybase's CodeXchange.
I am using this code, try it!
//// Profile access databases accdb format
SQLCA.DBMS = "OLE DB"
SQLCA.AutoCommit = False
SQLCA.DBParm = "PROVIDER='Microsoft.ACE.OLEDB.12.0',DATASOURCE='C:\databasename.accdb',DelimitIdentifier='No',CommitOnDisconnect='No'"
Connect using SQLCA;
If SQLCA.SQLCode = 0 Then
Open ( w_rsre_frame )
else
MessageBox ("Cannot Connect to Database", SQLCA.SQLErrText )
End If
or
//// Profile access databases mdb format
transaction aTrx
long resu
string database
database = "C:\databasename.mdb"
aTrx = create transaction
aTrx.DBMS = "OLE DB"
aTrx.AutoCommit = True
aTrx.DBParm = "PROVIDER='Microsoft.Jet.OLEDB.4.0',DATASOURCE='"+database+"',PBMaxBlobSize=100000,StaticBind='No',PBNoCatalog='YES'"
connect using aTrx ;
if atrx.sqldbcode = 0 then
messagebox("","Connection success to database")
else
messagebox("Error code: "+string(atrx.sqlcode),atrx.sqlerrtext+ " DB Code Error: "+string(atrx.sqldbcode))
end if
// do stuff...
destroy atrx

Resources