Showing posts with label express. Show all posts
Showing posts with label express. Show all posts

Friday, March 30, 2012

import OpenSSL certificate with private key into sql server 2005 express edtion

hey,

i have a problem, to import a self signed openssl certificate into the sql server 2005.

my final idea is to get encrypted columns from the database over an jdbc connection in a java client.

when i use a certificate generated by the sql server 2005, i can encryt columns of a table. then i catch the

the result in my java client. but in java, i need a keystore with the private key of the certificate.

ok. i have export the the certificate and the private key of the sql server 2005.

problem: in a keystore i can only import the certificate (signed public key) but not the private key.

my new idea is to import an openssl certificate or an certificate generated by the keytool (java) into the

sql server 2005 and encypt the data with the imported certificate. Problem: The SQL Server give me an

Exception: (Sorry i drag & drop the exception, is written in german)

Msg 15208, Level 16, State 1, Line 2

Die Datei für das Zertifikat, den asymmetrischen Schlüssel oder den privaten Schlüssel ist nicht vorhanden oder weist ein ungültiges Format auf.

My Import Statement is:

CREATE CERTIFICATE InsuranceCertOpenSSL

FROM

FILE = 'E:\master\keys\insuranceservice_tomcat_apr_x509_certificate_with_cygwin_openssl_20060630\insuranceservice_tomcat_x509_certificate_with_openssl.crt'

WITH PRIVATE KEY (

FILE = 'E:\master\keys\insuranceservice_tomcat_apr_x509_certificate_with_cygwin_openssl_20060630\insuranceservice_tomcat_x509_certificate_with_openssl_private.key',

DECRYPTION BY PASSWORD = 'testit2_',

ENCRYPTION BY PASSWORD = 'testit2_'

)

I use password encryption, and not the internal master key (or service master key)

Hope for help :)

nils

Hi Nils,

Could you try creating a certificate in keytool with a private key that is not encrypted? Then when you create it in SQL Server, you can omit the "DECRYPTION BY PASSWORD..." line.

It may simply be that the decryption of the certificate is failing.

Sung

|||

HI Sung,

thank you for answering.

i create a test certificate with private key in openssl and with keytool too.

i bring the certificate an the private key outside the sql server 2005 in the DER Format, because i read

that the certificate in SQL Server use this format.

OK.

i can import the certificate from openssl. (without the WITH PRIVATE KEY option).

CREATE CERTIFICATE InsuranceCertOpenSSL
FROM
FILE = 'E:\CertSqlServer2005InsuranceDatabaseOpenSSL.crt'

it work. but when i encrypt and decrypt somthing the sql server have no private key.

SELECT Cert_ID('InsuranceCertOenSSL')

DECLARE @.NAMEENC NVARCHAR(100)
DECLARE @.PWD NVARCHAR(100)
SELECT @.PWD = 'testit2_'
SELECT @.NAMEENC = EncryptByCert(Cert_ID('InsuranceCertOpenSSL'),N'O12345678901234MMM5678XXX901234567890 O12345678901234567')
SELECT @.NAMEENC as encode
SELECT CAST(DecryptByCert(Cert_ID('InsuranceCertOpenSSL'),@.NAMEENC, @.PWD) AS NVARCHAR(MAX)) as decode
GO

Result is null.

OK:

When i import the certificate with an private key.

CREATE CERTIFICATE InsuranceCertOpenSSL
FROM
FILE = 'E:\insuranceservice_tomcat_x509_certificate_with_openssl_DER.crt'
WITH PRIVATE KEY (
FILE = 'E:\insuranceservice_tomcat_x509_certificate_with_openssl_private_DER.key',
DECRYPTION BY PASSWORD = 'testit2_',
ENCRYPTION BY PASSWORD = 'testit2_'
)

it doesn' t work.

my problem is that the sql server 2005 enrcypt the private key by export. also the sql server 2005 import only a encrypted private key.

when the key is encrypted i can not convert into PEM. (with openssl)

My destination is to have encrpted data in my java application. and there i will decrypt.

two ways...

1.) import an expernal generated certificate and private key. this must be imported into the sql server. PROBLEM: can not import the private key (must by encrypted, i think so)

or

2.) create an certificate in sql server 2005 with private key. export both. (DER-Format). To convert the certificate into PEM is no problem. but to convert the private key into pem, openssl give me an exception:

$ openssl rsa -inform DER -in CertSqlServer2005InsuranceDatabase_private.key -o
ut CertSqlServer2005InsuranceDatabase_private_PEM.key -outform PEM
unable to load Private Key
6944:error:0D07207B:asn1 encoding routines:ASN1_get_object:header too long:asn1_
lib.c:150:

I will map this to import the certificate and the key into an keystore and opened in java.

3.) a new idea: encrpt by a symmetric key. but these keys can not be exported from the database. (but recreate in the database)

in the moment i try to create a equivalent symmetric key with openssl .

i don't know the best way. but i need one way. please help

thank you

nils

|||

I looked through the keytool documentation and it does not seem to support the private key file format that SQL Server expects.

How exactly did you create the private key files that you were trying to import in SQL Server?

You may want to use another tool to generate your certificate. Have you tried using makecert to generate the certificates?

Thanks
Laurentiu

|||

Hi Nils,

[Edit - see Laurentiu's comment above]

We do recommend using symmetric keys for encryption as the performance gain is significant, but you are right that they currently cannot be exported.

Do you have to do decryption on both the application and the database? It kind of sounds like you want the database to be able to encrypt and then your application will handle the decryption? If this is the case, you can possibly get around this by storing the full certificate (public/private key pair) with the application and storing only the public key of the ceriticate on the database. You should not need the private key to encrypt data, you only need the private key to decrypt.

Hope this helps,

Sung

|||

Hi Sung,

thanks for your help.

yes you are right. i create an application with web services an database connects. in the application will have the chance to distribute my "moduls". i know i can you ssl. in some parts i use it. but to connect to an database i dont't know to connect to the database over ssl. ok, i can programm a Listener-Thread on the database site, but for many connection i need a connection pool. this is not what i want.

you are right, i can create an external certificate/private key and use it to encrpt and decrypt outside the database. and the database encrypt only data. (i must think about, for a solution that i realy need the decryption in the database. i can encrypt only data-column, and not the searching-keys, and so on.)

soloution 1 (your):

create external certificate with openssl (for example) and encrypt on in the database with the imported certificate (without the private key).

solution 2:

create a symmetirc key in the application and the same in the database:

2.a.) in the database

CREATE SYMMETRIC KEY InsuranceSymDESKey
WITH
ALGORITHM = DES,
KEY_SOURCE = 'testit2_',
IDENTITY_VALUE = 'id_insurance_service_center'
ENCRYPTION BY CERTIFICATE InsuranceCert
go

2.b.) with openssl

openssl des -out insurance_sql_server_symmetric_key_openssl.key - ....

sorry i don't know the right syntax, to generated the same key. is this possible?

nils


|||

HI Cristofor,

>> I looked through the keytool documentation and it does not seem to support the private key file format that SQL Server expects.

The exported SQL Server Certificates in DER-Format. With

openssl x509 -in CertSqlServer2005InsuranceDatabase.crt -inform DER -out CertSqlServer2005InsuranceDatabase_PEM.crt -outform PEM
you can transform the certificate. Is that realy a differnet format for the primary key or is the exported key from the sql server only additional encrypted? In the sql server documentation is only reported that the key is encrypted, but no information about the algorithm or so.

>> How exactly did you create the private key files that you were trying to import in SQL Server?

1.) generate key

$ openssl genrsa -out insuranceservice_tomcat_x509_certificate_with_openssl_private.key -des3 2048

2.) create request

$ openssl req -new -in insuranceservice_tomcat_x509_certificate_with_openssl_private.key -out insuranceservice_tomcat_x509_certificate_with_openssl.csr

3.) create certificate

$ openssl x509 -in insuranceservice_tomcat_x509_certificate_with_openssl.csr -out insuranceservice_tomcat_x509_certificate_with_openssl.crt -req -signkey insuranceservice_tomcat_x509_certificate_with_openssl_private.key -days 365

4.) map private key from PEM into DER

$ openssl rsa -inform PEM -in insuranceservice_tomcat_x509_certificate_with_openssl_private.key -outform DER -out insuranceservice_tomcat_x509_certificate_with_openssl_private_DER.key -des3

5.) map crt from PEM into DER

$ openssl x509 -in insuranceservice_tomcat_x509_certificate_with_openssl.crt -inform PEM -out insuranceservice_tomcat_x509_certificate_with_openssl_DER.crt -outform DER

IMPORT into the sql server:

1.) (works, but without the private key)

CREATE CERTIFICATE InsuranceCertOpenSSL
FROM
FILE = 'E:\insuranceservice_tomcat_x509_certificate_with_openssl_DER.crt'

2.) doesn't work

CREATE CERTIFICATE InsuranceCertOpenSSL
FROM
FILE = 'E:\insuranceservice_tomcat_x509_certificate_with_openssl_DER.crt'
WITH PRIVATE KEY (
FILE = 'E:\insuranceservice_tomcat_x509_certificate_with_openssl_private_DER.key',
DECRYPTION BY PASSWORD = 'testit2_',
ENCRYPTION BY PASSWORD = 'testit2_'
)

When i remove the decryption, it doesn't work also.

>> You may want to use another tool to generate your certificate. Have you tried using makecert to generate the certificates?

i don't know the tool. but often the tools using in the background the openssl. You think this tool make another format the the sql server can understand (only the private key is needed).

i don't know the best way. but i will only send encrypted data over the network.

On which site i create the certificate (openssl or sql server) an then import and use each other is not imported.

also is not imported which tool i use to create the certificate/private key. i use all what give me an solution.

The problems are:

1.) import an certificate and the private key into the sql server 2005, generates by another software like the sql server 2005

2.) use the exported certificate and the private key from a sql server 2005.

In an microsoft document (http://www.microsoft.com/germany/technet/itsolutions/msit/security/sqldatsec.mspx) (german) i found in the last paragraph an information, that only certificates and private key can exchange between two or more sql server 2005. is this right?

Nils

|||

Hey Nils,

In regards to the connection problem, I will have to research that further.

I was trying to figure out a good solution for your second approach and I ran across two problems:

1) SQL Server and OpenSSL are probably generating the keys differently, therefore the keys created in 2a and 2b probably won't work with each other

2) I was talking about this with Raul and he mentioned that beyond that, the encrypted data is stored with extra headers and other info so it's not easy to extract the raw cipher text.

I'm not sure how to get around these two issues. The other alternative is to use JCE to handle encryption and decryption completely externally?

Sung

|||

It seems to me like you are trying to protect the data in transit, not only at rest. I strongly recommend against using the secret storage features in SQL Server 2005 for data in transit protection, instead, I would recommend using SSL between you server and client. You can find more information on this topic in MSDN (Encrypting Connections to SQL Server http://msdn2.microsoft.com/en-us/library/ms189067.aspx).

If my assumption is incorrect and/or you still need to be able to encrypt data in both your client application and SQL Server your best option would be to use certificates generated by makecert as Laurentiu mentioned.

Unfortunately the OpenSSL format for private keys and PVK are not compatible, but you can generate the certificate (public CER file and private key in PVK) using makecert, then to use it on OpenSSL you can use pvk2pfx tool to generate a PFX, as far as I remember, OpenSSL should be able to use DER encoded PFX files.

For the second solution you mentioned, creating the same symmetric key outside SQL Server. While in theory it is possible (KEY_SOURCE uses CAPI CryptDeriveKey to generate a 3DES key), you will face with the SQL Server specific headers that are not properly part of the ciphertext as well as the encrypted header once you are able to decrypt the data. I would strongly recommend against this approach.

I also include a link to a different discussion in the forum with a similar scenario (using an asymmetric key in a client), but in this case the client was using .NET code; while not exactly your scenario, it may be useful.

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=384472&SiteID=1

I hope this information was useful,

-Raul Garcia

SDE/T

SQL Server Engine

|||

Hi Nils,

makecert is a Microsoft certificate creation utility. It can generate certificates in the format that SQL Server 2005 understands. You can convert those certificates to other formats, such as PFX, using other tools (see http://www.kinook.com/blog/?p=10). I think openssl should know how to read PFX files, but I amy not familiar with openssl or keytool. My suggestion is to generate a certificate using makecert in the format understood by SQL Server, then convert it to PFX and use it with your application.

Thanks
Laurentiu

PS: My name is Laurentiu, Cristofor is my last name.

|||

Thanks to all for help. (and sorry for the mistake with your name laurentiu.)

a.) i use the pvktool to change the header of the certificates. transform the private key.

pvk -in CertSqlServer2005InsuranceDatabase_PVK_private.key -out CertSqlServer2005InsuranceDatabase_PEM_private.key

b.) transform the certificate

openssl x509 -in CertSqlServer2005InsuranceDatabase_DER.crt -inform DER -out CertSqlServer2005InsuranceDatabase_PEM.crt -outform PEM

c.) produce a keystore (pkcs12 format)

openssl pkcs12 -export -in CertSqlServer2005InsuranceDatabase_PEM.crt -inkey CertSqlServer2005InsuranceDatabase_PEM_private.key -out insuranceservice_sql_server_keystore_PKCS12.jks -name insurance_sql_server_cert

d) from java it is easer to work with jks-format keystore


set ksFileIn=insuranceservice_sql_server_keystore_PKCS12.jks
set ksFileOut=insuranceservice_sql_server_keystore_JKS.jks
set keyAlias=insurance_sql_server_cert
set ksPass=testit2_

java testclient.CopyKeyAndCertFrom_PKCS12_To_JKS_KeyStore %ksFileIn% %ksFileOut% %keyAlias% %ksPass%

e.) for this i write a small java programm (testclient.CopyKeyAndCertFrom_PKCS12_To_JKS_KeyStore)

package testclient;

import java.io.*;
import java.util.*;
import java.security.UnrecoverableKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.KeyStoreException;
import java.security.KeyStore;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Key;
import java.security.cert.Certificate;
import java.security.spec.*;

public class CopyKeyAndCertFrom_PKCS12_To_JKS_KeyStore {
public static void main(String[] args) {
try {
System.out.println("Usage: CreateSQLServerKeyStore <pkcs12_keystore_in> <jks_keystore_out>"
+ "<key alias> <keystore password>");

System.out.print("\nstart");


if (args.length != 4) {
System.exit(-1);
}

String ksFileIn = args[0];
String ksFileOutJava = args[1];
String keyAlias = args[2];
char[] ksPass = args[3].toCharArray();

KeyStore ksJKS = KeyStore.getInstance("JKS");
ksJKS.load(null, ksPass);

KeyStore ksPKCS12 = KeyStore.getInstance("PKCS12");
java.io.FileInputStream fis = new FileInputStream(ksFileIn);
ksPKCS12.load(fis, ksPass);

java.security.Key key = null;
java.security.PublicKey publicKey = null;
java.security.cert.Certificate cert = null;
java.security.cert.Certificate[] certChain = new java.security.cert.Certificate[1];

key = ksPKCS12.getKey(keyAlias, ksPass);
if (key instanceof java.security.PrivateKey) {
cert = ksPKCS12.getCertificate(keyAlias);
certChain = ksPKCS12.getCertificateChain(keyAlias);
publicKey = cert.getPublicKey();
}

ksJKS.setKeyEntry(keyAlias, key, ksPass, certChain);

FileOutputStream fos = new FileOutputStream(ksFileOutJava);
ksJKS.store(fos, ksPass);
fos.close();

System.out.print("\nend");
} catch (Exception e) {
System.out.print(e);
}
}
}

e.) for testing (it works also) (makecert)

makecert -r -cy end -sky exchange -n "CN=Nils" -b 01/01/2006 -e 01/01/2011 -a sha1 -sv CertSqlServer2005InsuranceDatabase_makecert_x509_private_key.pvk CertSqlServer2005InsuranceDatabase_makecert_x509.cer

f.) after this you can import the certificate and the private key into the sql server 2005. in java you can also open the

private key and the certificate from the keystore.

...

FileInputStream fis = null;
KeyStore ks = null;
Key key = null;
PrivateKey privateKey = null;
PublicKey publicKey = null;
Certificate cert = null;
Cipher cipher = null;
String encryptedstring = null;
String decryptedstring = null;
byte[] encryptedtext = null;
byte[] decryptedtext = null;

fis = new FileInputStream(dbKeyStore);
ks = KeyStore.getInstance(dbKeyStoreTyp);
ks.load(fis, dbKeyStorePass);
key = ks.getKey(dbKeyStoreAlias, dbKeyStorePass);
if (key instanceof PrivateKey) {
privateKey = (PrivateKey) key;
cert = ks.getCertificate(dbKeyStoreAlias);
publicKey = cert.getPublicKey();
}

Security.addProvider(new BouncyCastleProvider());
cipher = Cipher.getInstance("RSA/1/NoPadding", "BC");
...

Now i can encrypt an decrpyt. BUT i have another problem.

In the sql server 2005 the DecryptByCert and the EnrcyptByCert Method give as the result the datatype varbinary(128).

ok. But the SQL Server doesn't give me the data. for example i write some sql statements.

drop table dbo.TestSec
go

CREATE TABLE dbo.TestSec
( MandantenVerbindungID nvarchar(5) NOT NULL,
MandantenBezeichnungKurz1 varbinary(128) NOT NULL
);
GO

INSERT into dbo.TestSec (MandantenVerbindungID,MandantenBezeichnungKurz1)
values ('NBIT1', EncryptByCert(Cert_ID('InsuranceCert'), N'NBIT1'))
GO

--(1. First SELECT STATEMENT)


SELECT MandantenVerbindungID,
DecryptByCert(Cert_ID('InsuranceCert'), MandantenBezeichnungKurz1, N'testit2_')
FROM dbo.TestSec

Result:

-- 1.Column: NBIT1
-- 2.Column: 0x4E004200490054003100

--(2. Second SELECT STATEMENT)

Select MandantenVerbindungID, MandantenBezeichnungKurz1 from dbo.TestSec


-- 1.Column: NBIT1
-- 2.Column: 0x6FF1AD39946A3C92E16E035446F66930852CA086BECEE05FE1AD95DD578A8281169DF696E3528580B35C9CCEB7AB
5DBBEE4C7F9FB34F75460A2A0DECAA146FD8F8CF9A258D49C2B1A8012918609F9C4CDF53A1439CEEFF21CCE2076DE
166BB123AD2788D2B8BE3BD1F4E967FFEFC84D839C485596CC8556641387D891224914

--(3. Third SELECT STATEMENT) (ONLY for Test)
Select MandantenVerbindungID, convert(varbinary(128),MandantenBezeichnungKurz1) from dbo.TestSec

When i select the data with the first select statement i get the needed HEX-Values to decrypt. But when i make a

normal select (2. statement) i get 128 Byte Hex Code. But i need the result of the first statement.

OK: i can write the same statement in java an start. but then goes the password in plaintext across the network. Me idea was to get the encrypted data.

now i have the chance to encrypt but i have no data :)))))) sorry i must smile.

nils

|||

You cannot retrieve the cleartext data without decrypting it, so statement (1) will get the cleartext data, while statement (2) will get the ciphertext - that is to be expected. If you do not want to specify a password in statement (1), then you should create the SQL Server certificate such that it is encrypted by the database master key (that is the behavior if you don't specify a password during the creation of the certificate) - then you won't need to specify any password to use it for decryption.

Thanks
Laurentiu

|||

hi Laurentiu,

you are right. in this moment i see it. but i am unhappy. i have on both site (sql server and java) the keys and the certificate. i print out the key store, and have a look at it. i think i have the same certificate. but it doesn't work.

i test it and test it ... nothing.

i get the enrypted data from the ResultSet with getString (0x...) or by getBytes(). i convert the data into UTF-8 and so on. no result.

now i think i must change my way and create an ssl connection. but i have test it in the sql server configuration manager. change the protocol to required encryption, but i can not select an certificate.

then i start the mmc and import an certificate for the current user (admin). no result.

have you any idea to import the certificate. and after this must i connect from my programm an sslSocket and tunnel through this my jdbc connect? or on which way it works. (i have an other example found, where an ssl client and ssl server is realized and only bethween this is the ssl conncet. then the ssl server connect to the sql server with a normal jdbc connect.. is this right?

thanks for all ideas

nils

|||

Wait a second, the results you were getting before were correct, yo did succeed to decrypt. Maybe you're getting confused because the result of the decryption is binary - you need to add a convert call to cast the binary to nvarchar: 0x4E004200490054003100 is NBIT1. Try executing:

select convert(nvarchar(20), 0x4E004200490054003100)

Or do you mean that you cannot decrypt on the Java application side?

For the SSL questions, you should ask on the SQL Server Data Access Forum.

Thanks
Laurentiu

|||

Encryption/Decryption using SQL Server 2005 key management performing cryptography operations in .NET

Thought this might help. I wasn't able to find documentation on this anywhere.

But I came up with a way to do this.

--SETUP--


makecert -r -pe -n "CN=crossmatch.net" -b 01/01/2000 -e 01/01/2036 -eku 1.3.6.1.5.5.7.3.1 -sky exchange -sy 12 -sv {PRIVATE KEY}.pvk {CERTIFICATE}.cer
cert2spc {CERTIFICATE}.cer {CERTIFICATE}.spc
pvk2pfx -pvk {PRIVATE KEY}.pvk -pi {PASSWORD - create at this point} -spc {CERTIFICATE}.spc -pfx {CERTIFICATE}.pfx


CREATE CERTIFICATE {CERTIFICATE_NAME}
FROM FILE = '{CERTIFICATE}.cer'
WITH PRIVATE KEY (FILE = '{PRIVATE KEY}.pvk',
DECRYPTION BY PASSWORD = '{PASSWORD}');

CLR


public class SqlCryptography
{
string m_FileName;
string m_PKeyPassword;
X509Certificate2 m_Certificate;
RSACryptoServiceProvider m_Encryptor;
RSACryptoServiceProvider m_Decryptor;

public string FileName
{
get{ return m_FileName; }
set{ m_FileName = value; }
}

public string PKeyPassword
{
get{ return m_PKeyPassword; }
set{ m_PKeyPassword = value; }
}

X509Certificate2 Certificate
{
get{

if( m_Certificate == null )
m_Certificate = new X509Certificate2( m_FileName, m_PKeyPassword );
return m_Certificate;
}
}

RSACryptoServiceProvider Encryptor
{
get{
if( m_Encryptor == null )
m_Encryptor = ( RSACryptoServiceProvider ) Certificate.PublicKey.Key;
return m_Encryptor;
}
}

RSACryptoServiceProvider Decryptor
{
get{
if( m_Decryptor == null )
m_Decryptor = ( RSACryptoServiceProvider ) Certificate.PrivateKey;
return m_Decryptor;
}
}

public SqlCryptography( ) : this( string.Empty, null )
{

}

public SqlCryptography( string certificateFileName, string password )
{
this.m_FileName = certificateFileName;
this.m_PKeyPassword = password;
}


public byte[] Encrypt( byte[] data )
{
return Encryptor.Encrypt( data, false );
}

public byte[] Decrypt( byte[] encryptedData )
{
return Decryptor.Decrypt( encryptedData, false );
}
}

IMPLEMENT

MAXIMUM BYTE[] LENGTH IS 117

crypt.SqlCryptography crypto = new crypt.SqlCryptography( @."C:\Users\Matt\CrossMatch.Security.pfx", "crossmatch" );
Encoding.Default.GetString( crypto.Decrypt( crypto.Encrypt( Encoding.Default.GetBytes( "TEST" ) ) ) );
Encoding.Default.GetString( crypto.Decrypt( crypto.Encrypt( Encoding.Default.GetBytes( "TEST TEST" ) ) ) );

Note: Importing the pfx into a certificate store you will lose the private key on the cert.

import OpenSSL certificate with private key into sql server 2005 express edtion

hey,

i have a problem, to import a self signed openssl certificate into the sql server 2005.

my final idea is to get encrypted columns from the database over an jdbc connection in a java client.

when i use a certificate generated by the sql server 2005, i can encryt columns of a table. then i catch the

the result in my java client. but in java, i need a keystore with the private key of the certificate.

ok. i have export the the certificate and the private key of the sql server 2005.

problem: in a keystore i can only import the certificate (signed public key) but not the private key.

my new idea is to import an openssl certificate or an certificate generated by the keytool (java) into the

sql server 2005 and encypt the data with the imported certificate. Problem: The SQL Server give me an

Exception: (Sorry i drag & drop the exception, is written in german)

Msg 15208, Level 16, State 1, Line 2

Die Datei für das Zertifikat, den asymmetrischen Schlüssel oder den privaten Schlüssel ist nicht vorhanden oder weist ein ungültiges Format auf.

My Import Statement is:

CREATE CERTIFICATE InsuranceCertOpenSSL

FROM

FILE = 'E:\master\keys\insuranceservice_tomcat_apr_x509_certificate_with_cygwin_openssl_20060630\insuranceservice_tomcat_x509_certificate_with_openssl.crt'

WITH PRIVATE KEY (

FILE = 'E:\master\keys\insuranceservice_tomcat_apr_x509_certificate_with_cygwin_openssl_20060630\insuranceservice_tomcat_x509_certificate_with_openssl_private.key',

DECRYPTION BY PASSWORD = 'testit2_',

ENCRYPTION BY PASSWORD = 'testit2_'

)

I use password encryption, and not the internal master key (or service master key)

Hope for help :)

nils

Hi Nils,

Could you try creating a certificate in keytool with a private key that is not encrypted? Then when you create it in SQL Server, you can omit the "DECRYPTION BY PASSWORD..." line.

It may simply be that the decryption of the certificate is failing.

Sung

|||

HI Sung,

thank you for answering.

i create a test certificate with private key in openssl and with keytool too.

i bring the certificate an the private key outside the sql server 2005 in the DER Format, because i read

that the certificate in SQL Server use this format.

OK.

i can import the certificate from openssl. (without the WITH PRIVATE KEY option).

CREATE CERTIFICATE InsuranceCertOpenSSL
FROM
FILE = 'E:\CertSqlServer2005InsuranceDatabaseOpenSSL.crt'

it work. but when i encrypt and decrypt somthing the sql server have no private key.

SELECT Cert_ID('InsuranceCertOenSSL')

DECLARE @.NAMEENC NVARCHAR(100)
DECLARE @.PWD NVARCHAR(100)
SELECT @.PWD = 'testit2_'
SELECT @.NAMEENC = EncryptByCert(Cert_ID('InsuranceCertOpenSSL'),N'O12345678901234MMM5678XXX901234567890 O12345678901234567')
SELECT @.NAMEENC as encode
SELECT CAST(DecryptByCert(Cert_ID('InsuranceCertOpenSSL'),@.NAMEENC, @.PWD) AS NVARCHAR(MAX)) as decode
GO

Result is null.

OK:

When i import the certificate with an private key.

CREATE CERTIFICATE InsuranceCertOpenSSL
FROM
FILE = 'E:\insuranceservice_tomcat_x509_certificate_with_openssl_DER.crt'
WITH PRIVATE KEY (
FILE = 'E:\insuranceservice_tomcat_x509_certificate_with_openssl_private_DER.key',
DECRYPTION BY PASSWORD = 'testit2_',
ENCRYPTION BY PASSWORD = 'testit2_'
)

it doesn' t work.

my problem is that the sql server 2005 enrcypt the private key by export. also the sql server 2005 import only a encrypted private key.

when the key is encrypted i can not convert into PEM. (with openssl)

My destination is to have encrpted data in my java application. and there i will decrypt.

two ways...

1.) import an expernal generated certificate and private key. this must be imported into the sql server. PROBLEM: can not import the private key (must by encrypted, i think so)

or

2.) create an certificate in sql server 2005 with private key. export both. (DER-Format). To convert the certificate into PEM is no problem. but to convert the private key into pem, openssl give me an exception:

$ openssl rsa -inform DER -in CertSqlServer2005InsuranceDatabase_private.key -o
ut CertSqlServer2005InsuranceDatabase_private_PEM.key -outform PEM
unable to load Private Key
6944:error:0D07207B:asn1 encoding routines:ASN1_get_object:header too long:asn1_
lib.c:150:

I will map this to import the certificate and the key into an keystore and opened in java.

3.) a new idea: encrpt by a symmetric key. but these keys can not be exported from the database. (but recreate in the database)

in the moment i try to create a equivalent symmetric key with openssl .

i don't know the best way. but i need one way. please help

thank you

nils

|||

I looked through the keytool documentation and it does not seem to support the private key file format that SQL Server expects.

How exactly did you create the private key files that you were trying to import in SQL Server?

You may want to use another tool to generate your certificate. Have you tried using makecert to generate the certificates?

Thanks
Laurentiu

|||

Hi Nils,

[Edit - see Laurentiu's comment above]

We do recommend using symmetric keys for encryption as the performance gain is significant, but you are right that they currently cannot be exported.

Do you have to do decryption on both the application and the database? It kind of sounds like you want the database to be able to encrypt and then your application will handle the decryption? If this is the case, you can possibly get around this by storing the full certificate (public/private key pair) with the application and storing only the public key of the ceriticate on the database. You should not need the private key to encrypt data, you only need the private key to decrypt.

Hope this helps,

Sung

|||

Hi Sung,

thanks for your help.

yes you are right. i create an application with web services an database connects. in the application will have the chance to distribute my "moduls". i know i can you ssl. in some parts i use it. but to connect to an database i dont't know to connect to the database over ssl. ok, i can programm a Listener-Thread on the database site, but for many connection i need a connection pool. this is not what i want.

you are right, i can create an external certificate/private key and use it to encrpt and decrypt outside the database. and the database encrypt only data. (i must think about, for a solution that i realy need the decryption in the database. i can encrypt only data-column, and not the searching-keys, and so on.)

soloution 1 (your):

create external certificate with openssl (for example) and encrypt on in the database with the imported certificate (without the private key).

solution 2:

create a symmetirc key in the application and the same in the database:

2.a.) in the database

CREATE SYMMETRIC KEY InsuranceSymDESKey
WITH
ALGORITHM = DES,
KEY_SOURCE = 'testit2_',
IDENTITY_VALUE = 'id_insurance_service_center'
ENCRYPTION BY CERTIFICATE InsuranceCert
go

2.b.) with openssl

openssl des -out insurance_sql_server_symmetric_key_openssl.key - ....

sorry i don't know the right syntax, to generated the same key. is this possible?

nils


|||

HI Cristofor,

>> I looked through the keytool documentation and it does not seem to support the private key file format that SQL Server expects.

The exported SQL Server Certificates in DER-Format. With

openssl x509 -in CertSqlServer2005InsuranceDatabase.crt -inform DER -out CertSqlServer2005InsuranceDatabase_PEM.crt -outform PEM
you can transform the certificate. Is that realy a differnet format for the primary key or is the exported key from the sql server only additional encrypted? In the sql server documentation is only reported that the key is encrypted, but no information about the algorithm or so.

>> How exactly did you create the private key files that you were trying to import in SQL Server?

1.) generate key

$ openssl genrsa -out insuranceservice_tomcat_x509_certificate_with_openssl_private.key -des3 2048

2.) create request

$ openssl req -new -in insuranceservice_tomcat_x509_certificate_with_openssl_private.key -out insuranceservice_tomcat_x509_certificate_with_openssl.csr

3.) create certificate

$ openssl x509 -in insuranceservice_tomcat_x509_certificate_with_openssl.csr -out insuranceservice_tomcat_x509_certificate_with_openssl.crt -req -signkey insuranceservice_tomcat_x509_certificate_with_openssl_private.key -days 365

4.) map private key from PEM into DER

$ openssl rsa -inform PEM -in insuranceservice_tomcat_x509_certificate_with_openssl_private.key -outform DER -out insuranceservice_tomcat_x509_certificate_with_openssl_private_DER.key -des3

5.) map crt from PEM into DER

$ openssl x509 -in insuranceservice_tomcat_x509_certificate_with_openssl.crt -inform PEM -out insuranceservice_tomcat_x509_certificate_with_openssl_DER.crt -outform DER

IMPORT into the sql server:

1.) (works, but without the private key)

CREATE CERTIFICATE InsuranceCertOpenSSL
FROM
FILE = 'E:\insuranceservice_tomcat_x509_certificate_with_openssl_DER.crt'

2.) doesn't work

CREATE CERTIFICATE InsuranceCertOpenSSL
FROM
FILE = 'E:\insuranceservice_tomcat_x509_certificate_with_openssl_DER.crt'
WITH PRIVATE KEY (
FILE = 'E:\insuranceservice_tomcat_x509_certificate_with_openssl_private_DER.key',
DECRYPTION BY PASSWORD = 'testit2_',
ENCRYPTION BY PASSWORD = 'testit2_'
)

When i remove the decryption, it doesn't work also.

>> You may want to use another tool to generate your certificate. Have you tried using makecert to generate the certificates?

i don't know the tool. but often the tools using in the background the openssl. You think this tool make another format the the sql server can understand (only the private key is needed).

i don't know the best way. but i will only send encrypted data over the network.

On which site i create the certificate (openssl or sql server) an then import and use each other is not imported.

also is not imported which tool i use to create the certificate/private key. i use all what give me an solution.

The problems are:

1.) import an certificate and the private key into the sql server 2005, generates by another software like the sql server 2005

2.) use the exported certificate and the private key from a sql server 2005.

In an microsoft document (http://www.microsoft.com/germany/technet/itsolutions/msit/security/sqldatsec.mspx) (german) i found in the last paragraph an information, that only certificates and private key can exchange between two or more sql server 2005. is this right?

Nils

|||

Hey Nils,

In regards to the connection problem, I will have to research that further.

I was trying to figure out a good solution for your second approach and I ran across two problems:

1) SQL Server and OpenSSL are probably generating the keys differently, therefore the keys created in 2a and 2b probably won't work with each other

2) I was talking about this with Raul and he mentioned that beyond that, the encrypted data is stored with extra headers and other info so it's not easy to extract the raw cipher text.

I'm not sure how to get around these two issues. The other alternative is to use JCE to handle encryption and decryption completely externally?

Sung

|||

It seems to me like you are trying to protect the data in transit, not only at rest. I strongly recommend against using the secret storage features in SQL Server 2005 for data in transit protection, instead, I would recommend using SSL between you server and client. You can find more information on this topic in MSDN (Encrypting Connections to SQL Server http://msdn2.microsoft.com/en-us/library/ms189067.aspx).

If my assumption is incorrect and/or you still need to be able to encrypt data in both your client application and SQL Server your best option would be to use certificates generated by makecert as Laurentiu mentioned.

Unfortunately the OpenSSL format for private keys and PVK are not compatible, but you can generate the certificate (public CER file and private key in PVK) using makecert, then to use it on OpenSSL you can use pvk2pfx tool to generate a PFX, as far as I remember, OpenSSL should be able to use DER encoded PFX files.

For the second solution you mentioned, creating the same symmetric key outside SQL Server. While in theory it is possible (KEY_SOURCE uses CAPI CryptDeriveKey to generate a 3DES key), you will face with the SQL Server specific headers that are not properly part of the ciphertext as well as the encrypted header once you are able to decrypt the data. I would strongly recommend against this approach.

I also include a link to a different discussion in the forum with a similar scenario (using an asymmetric key in a client), but in this case the client was using .NET code; while not exactly your scenario, it may be useful.

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=384472&SiteID=1

I hope this information was useful,

-Raul Garcia

SDE/T

SQL Server Engine

|||

Hi Nils,

makecert is a Microsoft certificate creation utility. It can generate certificates in the format that SQL Server 2005 understands. You can convert those certificates to other formats, such as PFX, using other tools (see http://www.kinook.com/blog/?p=10). I think openssl should know how to read PFX files, but I amy not familiar with openssl or keytool. My suggestion is to generate a certificate using makecert in the format understood by SQL Server, then convert it to PFX and use it with your application.

Thanks
Laurentiu

PS: My name is Laurentiu, Cristofor is my last name.

|||

Thanks to all for help. (and sorry for the mistake with your name laurentiu.)

a.) i use the pvktool to change the header of the certificates. transform the private key.

pvk -in CertSqlServer2005InsuranceDatabase_PVK_private.key -out CertSqlServer2005InsuranceDatabase_PEM_private.key

b.) transform the certificate

openssl x509 -in CertSqlServer2005InsuranceDatabase_DER.crt -inform DER -out CertSqlServer2005InsuranceDatabase_PEM.crt -outform PEM

c.) produce a keystore (pkcs12 format)

openssl pkcs12 -export -in CertSqlServer2005InsuranceDatabase_PEM.crt -inkey CertSqlServer2005InsuranceDatabase_PEM_private.key -out insuranceservice_sql_server_keystore_PKCS12.jks -name insurance_sql_server_cert

d) from java it is easer to work with jks-format keystore


set ksFileIn=insuranceservice_sql_server_keystore_PKCS12.jks
set ksFileOut=insuranceservice_sql_server_keystore_JKS.jks
set keyAlias=insurance_sql_server_cert
set ksPass=testit2_

java testclient.CopyKeyAndCertFrom_PKCS12_To_JKS_KeyStore %ksFileIn% %ksFileOut% %keyAlias% %ksPass%

e.) for this i write a small java programm (testclient.CopyKeyAndCertFrom_PKCS12_To_JKS_KeyStore)

package testclient;

import java.io.*;
import java.util.*;
import java.security.UnrecoverableKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.KeyStoreException;
import java.security.KeyStore;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Key;
import java.security.cert.Certificate;
import java.security.spec.*;

public class CopyKeyAndCertFrom_PKCS12_To_JKS_KeyStore {
public static void main(String[] args) {
try {
System.out.println("Usage: CreateSQLServerKeyStore <pkcs12_keystore_in> <jks_keystore_out>"
+ "<key alias> <keystore password>");

System.out.print("\nstart");


if (args.length != 4) {
System.exit(-1);
}

String ksFileIn = args[0];
String ksFileOutJava = args[1];
String keyAlias = args[2];
char[] ksPass = args[3].toCharArray();

KeyStore ksJKS = KeyStore.getInstance("JKS");
ksJKS.load(null, ksPass);

KeyStore ksPKCS12 = KeyStore.getInstance("PKCS12");
java.io.FileInputStream fis = new FileInputStream(ksFileIn);
ksPKCS12.load(fis, ksPass);

java.security.Key key = null;
java.security.PublicKey publicKey = null;
java.security.cert.Certificate cert = null;
java.security.cert.Certificate[] certChain = new java.security.cert.Certificate[1];

key = ksPKCS12.getKey(keyAlias, ksPass);
if (key instanceof java.security.PrivateKey) {
cert = ksPKCS12.getCertificate(keyAlias);
certChain = ksPKCS12.getCertificateChain(keyAlias);
publicKey = cert.getPublicKey();
}

ksJKS.setKeyEntry(keyAlias, key, ksPass, certChain);

FileOutputStream fos = new FileOutputStream(ksFileOutJava);
ksJKS.store(fos, ksPass);
fos.close();

System.out.print("\nend");
} catch (Exception e) {
System.out.print(e);
}
}
}

e.) for testing (it works also) (makecert)

makecert -r -cy end -sky exchange -n "CN=Nils" -b 01/01/2006 -e 01/01/2011 -a sha1 -sv CertSqlServer2005InsuranceDatabase_makecert_x509_private_key.pvk CertSqlServer2005InsuranceDatabase_makecert_x509.cer

f.) after this you can import the certificate and the private key into the sql server 2005. in java you can also open the

private key and the certificate from the keystore.

...

FileInputStream fis = null;
KeyStore ks = null;
Key key = null;
PrivateKey privateKey = null;
PublicKey publicKey = null;
Certificate cert = null;
Cipher cipher = null;
String encryptedstring = null;
String decryptedstring = null;
byte[] encryptedtext = null;
byte[] decryptedtext = null;

fis = new FileInputStream(dbKeyStore);
ks = KeyStore.getInstance(dbKeyStoreTyp);
ks.load(fis, dbKeyStorePass);
key = ks.getKey(dbKeyStoreAlias, dbKeyStorePass);
if (key instanceof PrivateKey) {
privateKey = (PrivateKey) key;
cert = ks.getCertificate(dbKeyStoreAlias);
publicKey = cert.getPublicKey();
}

Security.addProvider(new BouncyCastleProvider());
cipher = Cipher.getInstance("RSA/1/NoPadding", "BC");
...

Now i can encrypt an decrpyt. BUT i have another problem.

In the sql server 2005 the DecryptByCert and the EnrcyptByCert Method give as the result the datatype varbinary(128).

ok. But the SQL Server doesn't give me the data. for example i write some sql statements.

drop table dbo.TestSec
go

CREATE TABLE dbo.TestSec
( MandantenVerbindungID nvarchar(5) NOT NULL,
MandantenBezeichnungKurz1 varbinary(128) NOT NULL
);
GO

INSERT into dbo.TestSec (MandantenVerbindungID,MandantenBezeichnungKurz1)
values ('NBIT1', EncryptByCert(Cert_ID('InsuranceCert'), N'NBIT1'))
GO

--(1. First SELECT STATEMENT)


SELECT MandantenVerbindungID,
DecryptByCert(Cert_ID('InsuranceCert'), MandantenBezeichnungKurz1, N'testit2_')
FROM dbo.TestSec

Result:

-- 1.Column: NBIT1
-- 2.Column: 0x4E004200490054003100

--(2. Second SELECT STATEMENT)

Select MandantenVerbindungID, MandantenBezeichnungKurz1 from dbo.TestSec


-- 1.Column: NBIT1
-- 2.Column: 0x6FF1AD39946A3C92E16E035446F66930852CA086BECEE05FE1AD95DD578A8281169DF696E3528580B35C9CCEB7AB
5DBBEE4C7F9FB34F75460A2A0DECAA146FD8F8CF9A258D49C2B1A8012918609F9C4CDF53A1439CEEFF21CCE2076DE
166BB123AD2788D2B8BE3BD1F4E967FFEFC84D839C485596CC8556641387D891224914

--(3. Third SELECT STATEMENT) (ONLY for Test)
Select MandantenVerbindungID, convert(varbinary(128),MandantenBezeichnungKurz1) from dbo.TestSec

When i select the data with the first select statement i get the needed HEX-Values to decrypt. But when i make a

normal select (2. statement) i get 128 Byte Hex Code. But i need the result of the first statement.

OK: i can write the same statement in java an start. but then goes the password in plaintext across the network. Me idea was to get the encrypted data.

now i have the chance to encrypt but i have no data :)))))) sorry i must smile.

nils

|||

You cannot retrieve the cleartext data without decrypting it, so statement (1) will get the cleartext data, while statement (2) will get the ciphertext - that is to be expected. If you do not want to specify a password in statement (1), then you should create the SQL Server certificate such that it is encrypted by the database master key (that is the behavior if you don't specify a password during the creation of the certificate) - then you won't need to specify any password to use it for decryption.

Thanks
Laurentiu

|||

hi Laurentiu,

you are right. in this moment i see it. but i am unhappy. i have on both site (sql server and java) the keys and the certificate. i print out the key store, and have a look at it. i think i have the same certificate. but it doesn't work.

i test it and test it ... nothing.

i get the enrypted data from the ResultSet with getString (0x...) or by getBytes(). i convert the data into UTF-8 and so on. no result.

now i think i must change my way and create an ssl connection. but i have test it in the sql server configuration manager. change the protocol to required encryption, but i can not select an certificate.

then i start the mmc and import an certificate for the current user (admin). no result.

have you any idea to import the certificate. and after this must i connect from my programm an sslSocket and tunnel through this my jdbc connect? or on which way it works. (i have an other example found, where an ssl client and ssl server is realized and only bethween this is the ssl conncet. then the ssl server connect to the sql server with a normal jdbc connect.. is this right?

thanks for all ideas

nils

|||

Wait a second, the results you were getting before were correct, yo did succeed to decrypt. Maybe you're getting confused because the result of the decryption is binary - you need to add a convert call to cast the binary to nvarchar: 0x4E004200490054003100 is NBIT1. Try executing:

select convert(nvarchar(20), 0x4E004200490054003100)

Or do you mean that you cannot decrypt on the Java application side?

For the SSL questions, you should ask on the SQL Server Data Access Forum.

Thanks
Laurentiu

|||

Encryption/Decryption using SQL Server 2005 key management performing cryptography operations in .NET

Thought this might help. I wasn't able to find documentation on this anywhere.

But I came up with a way to do this.

--SETUP--


makecert -r -pe -n "CN=crossmatch.net" -b 01/01/2000 -e 01/01/2036 -eku 1.3.6.1.5.5.7.3.1 -sky exchange -sy 12 -sv {PRIVATE KEY}.pvk {CERTIFICATE}.cer
cert2spc {CERTIFICATE}.cer {CERTIFICATE}.spc
pvk2pfx -pvk {PRIVATE KEY}.pvk -pi {PASSWORD - create at this point} -spc {CERTIFICATE}.spc -pfx {CERTIFICATE}.pfx


CREATE CERTIFICATE {CERTIFICATE_NAME}
FROM FILE = '{CERTIFICATE}.cer'
WITH PRIVATE KEY (FILE = '{PRIVATE KEY}.pvk',
DECRYPTION BY PASSWORD = '{PASSWORD}');

CLR


public class SqlCryptography
{
string m_FileName;
string m_PKeyPassword;
X509Certificate2 m_Certificate;
RSACryptoServiceProvider m_Encryptor;
RSACryptoServiceProvider m_Decryptor;

public string FileName
{
get{ return m_FileName; }
set{ m_FileName = value; }
}

public string PKeyPassword
{
get{ return m_PKeyPassword; }
set{ m_PKeyPassword = value; }
}

X509Certificate2 Certificate
{
get{

if( m_Certificate == null )
m_Certificate = new X509Certificate2( m_FileName, m_PKeyPassword );
return m_Certificate;
}
}

RSACryptoServiceProvider Encryptor
{
get{
if( m_Encryptor == null )
m_Encryptor = ( RSACryptoServiceProvider ) Certificate.PublicKey.Key;
return m_Encryptor;
}
}

RSACryptoServiceProvider Decryptor
{
get{
if( m_Decryptor == null )
m_Decryptor = ( RSACryptoServiceProvider ) Certificate.PrivateKey;
return m_Decryptor;
}
}

public SqlCryptography( ) : this( string.Empty, null )
{

}

public SqlCryptography( string certificateFileName, string password )
{
this.m_FileName = certificateFileName;
this.m_PKeyPassword = password;
}


public byte[] Encrypt( byte[] data )
{
return Encryptor.Encrypt( data, false );
}

public byte[] Decrypt( byte[] encryptedData )
{
return Decryptor.Decrypt( encryptedData, false );
}
}

IMPLEMENT

MAXIMUM BYTE[] LENGTH IS 117

crypt.SqlCryptography crypto = new crypt.SqlCryptography( @."C:\Users\Matt\CrossMatch.Security.pfx", "crossmatch" );
Encoding.Default.GetString( crypto.Decrypt( crypto.Encrypt( Encoding.Default.GetBytes( "TEST" ) ) ) );
Encoding.Default.GetString( crypto.Decrypt( crypto.Encrypt( Encoding.Default.GetBytes( "TEST TEST" ) ) ) );

Note: Importing the pfx into a certificate store you will lose the private key on the cert.

import one table from one database to another database

if i have one table from database A, and i want to copy the table to database B, then how to do it in SQL server management studio express? is it i have to make sql query?

try

select * into databaseB.dbo.TableA
from databaseA.dbo.TableA

or go to database B and run

select * into TableA
from databaseA.dbo.TableA

This will not copy constraints only data.

if it will not work right click on database and from task select import or export and select source destination , table to copy and run created SSIS package.

|||

i don't try yet the query. anyway, i right click on the database but i don't find any task that saying select import or export?

|||

i don't try yet the query. anyway, i right click on the database but i don't find any task that saying select import or export?

|||

Right click on your database in Object Explorer and in menu select tasks and next import export, Sorry it does not work in Management studio express, nut if you have SP1 and integration developments studio installed you can do it inside it.

Wednesday, March 28, 2012

Import MDF SQL 2000 file into SQL 2005 Express

Is it possible?
I only have the MDF from my SQL 2000 DB, and I need to import it to SQL
Server 2005...
Best Regards
Fabio CavassiniYou might try CREATE DATABASE...FOR ATTACH_REBUILD_LOG. This should work if
the database was properly detached from the SQL 2000 instance. See the SQL
2005 Books Online for more information.
Hope this helps.
Dan Guzman
SQL Server MVP
"Fabio Cavassini" <cavassinif@.gmail.com> wrote in message
news:1138068510.765889.178750@.g44g2000cwa.googlegroups.com...
> Is it possible?
> I only have the MDF from my SQL 2000 DB, and I need to import it to SQL
> Server 2005...
> Best Regards
> Fabio Cavassini
>|||Thanks Dan
I tried to attach it with sp_attach_db and it works...it converts the
format to the new version.
After that I got the following error when I want to create a Diagram:
"Database diagram support objects cannot be installed because this
database does not have a valid owner. To continue, first use the Files
page of the Database Properties dialog box or the ALTER AUTHORIZATION
statement to set the database owner to a valid login, then add the
database diagram support objects."
that this code fix...
EXEC sp_dbcmptlevel 'yourDB', '90';
go
ALTER AUTHORIZATION ON DATABASE::yourDB TO "yourLogin"
go
use [yourDB]
go
EXECUTE AS USER = N'dbo' REVERT
go
Best Regards
Fabio Cavassini|||> I tried to attach it with sp_attach_db and it works...it converts the
> format to the new version.
Just like the SQL 2000 version, sp_attach_db is basically just a wrapper for
CREATE DATABASE...FOR ATTACH. I don't recommend it in SQL 2005 because it
will be discontinued in a future version so you might as well get used to it
(or use a GUI that does this for you). From the SQL Server 2005 Books
Online:
<Excerpt
href="ms-help://MS.SQLCC.v9/MS.SQLSVR.v9.en/tsqlref9/html/59bc993e-7913-4091
-89cb-d2871cffda95.htm">
Important:
This feature will be removed in a future version of Microsoft SQL Server.
Avoid using this feature in new development work, and plan to modify
applications that currently use this feature. We recommend that you use
CREATE DATABASE database_name FOR ATTACH instead. For more information, see
CREATE DATABASE (Transact-SQL).
</Excerpt>
Hope this helps.
Dan Guzman
SQL Server MVP
"Fabio Cavassini" <cavassinif@.gmail.com> wrote in message
news:1138070344.185793.284520@.f14g2000cwb.googlegroups.com...
> Thanks Dan
> I tried to attach it with sp_attach_db and it works...it converts the
> format to the new version.
> After that I got the following error when I want to create a Diagram:
> "Database diagram support objects cannot be installed because this
> database does not have a valid owner. To continue, first use the Files
> page of the Database Properties dialog box or the ALTER AUTHORIZATION
> statement to set the database owner to a valid login, then add the
> database diagram support objects."
> that this code fix...
> EXEC sp_dbcmptlevel 'yourDB', '90';
> go
> ALTER AUTHORIZATION ON DATABASE::yourDB TO "yourLogin"
> go
> use [yourDB]
> go
> EXECUTE AS USER = N'dbo' REVERT
> go
> Best Regards
> Fabio Cavassini
>|||Thanks for the info Dan, I'll consider it.
Best Regards
Fabio Cavassinisql

Friday, March 23, 2012

Import from access db to sql express db

How do I import tables from an access db to sql Express?
reidarTHi
I did some testing on DEV edition and it works just file
SELECT *
FROM OPENDATASOURCE(
'Microsoft.Jet.OLEDB.4.0',
'Data Source="c:\northwind.mdb";
User ID=Admin;Password='
)...Customers
Take a look at linked servers in the BOL as well
"reidarT" <reidar@.eivon.no> wrote in message
news:%23S9JQgPoGHA.680@.TK2MSFTNGP03.phx.gbl...
> How do I import tables from an access db to sql Express?
> reidarT
>

Import from access db to sql express db

How do I import tables from an access db to sql Express?
reidarTHi
I did some testing on DEV edition and it works just file
SELECT *
FROM OPENDATASOURCE(
'Microsoft.Jet.OLEDB.4.0',
'Data Source="c:\northwind.mdb";
User ID=Admin;Password='
)...Customers
Take a look at linked servers in the BOL as well
"reidarT" <reidar@.eivon.no> wrote in message
news:%23S9JQgPoGHA.680@.TK2MSFTNGP03.phx.gbl...
> How do I import tables from an access db to sql Express?
> reidarT
>

Import flat file into SQL Server 2005 Express

I am new to SQL Server, and migrating part of an Access application to
SSE. I am trying to insert a comma delimited file into SSE 2005. I am
able to run a BULK INSERT statement on a simple file, specifying the
field (,) and row (\n) terminators. I can also do the same with a
format file.

Here is the problem. My csv file has 185 columns, with a mixture of
datatypes. Sometimes, a text field will contain the field delimiter as
part of the string. In this case (and only in this case) there will be
double quotes around the string to indicate that the comma is part of
the field, and not a delimiter.

Is there any way to indicate that there is a text delimiter that is
only present some of the time?

If not, any suggestions on getting the data into SSE?

Many thanks for your input.

Cheryl(cabrenner@.optonline.net) writes:

Quote:

Originally Posted by

I am new to SQL Server, and migrating part of an Access application to
SSE. I am trying to insert a comma delimited file into SSE 2005. I am
able to run a BULK INSERT statement on a simple file, specifying the
field (,) and row (\n) terminators. I can also do the same with a
format file.
>
Here is the problem. My csv file has 185 columns, with a mixture of
datatypes. Sometimes, a text field will contain the field delimiter as
part of the string. In this case (and only in this case) there will be
double quotes around the string to indicate that the comma is part of
the field, and not a delimiter.


So a file could look like this:

2,34,Enter Sandman,Pat Boone
9,34,Zabadak,"Dave, Dee, Dozy, Mich & Tich"
8,981,"Rebel, Rebel",David Bowie

There is now way to get BULK INSERT to handle this file in that shape.
If I were faced with this file, I would write Perl script that replaced
the commas outside the "" with a different delimiter and then removed the
"". And it would not be trivial.

Most other people would probably try to write a package in Integration
Services, but I have never used Integration Services myself. And for your
part - SQL Express does not come with Integration Services, I believe.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||In message <Xns98B096E86FA00Yazorman@.127.0.0.1>, Erland Sommarskog
<esquel@.sommarskog.sewrites

Quote:

Originally Posted by

(cabrenner@.optonline.net) writes:

Quote:

Originally Posted by

>I am new to SQL Server, and migrating part of an Access application to
>SSE. I am trying to insert a comma delimited file into SSE 2005. I am
>able to run a BULK INSERT statement on a simple file, specifying the
>field (,) and row (\n) terminators. I can also do the same with a
>format file.
>>
>Here is the problem. My csv file has 185 columns, with a mixture of
>datatypes. Sometimes, a text field will contain the field delimiter as
>part of the string. In this case (and only in this case) there will be
>double quotes around the string to indicate that the comma is part of
>the field, and not a delimiter.


>
>So a file could look like this:
>
2,34,Enter Sandman,Pat Boone
9,34,Zabadak,"Dave, Dee, Dozy, Mich & Tich"
8,981,"Rebel, Rebel",David Bowie
>
>There is now way to get BULK INSERT to handle this file in that shape.
>If I were faced with this file, I would write Perl script that replaced
>the commas outside the "" with a different delimiter and then removed the
>"". And it would not be trivial.
>
>Most other people would probably try to write a package in Integration
>Services, but I have never used Integration Services myself. And for your
>part - SQL Express does not come with Integration Services, I believe.


Two things to add, both useful options if the amount of data is small.
First, the import filters in MS Access are better than those in SQL
Server. If the data will fit into an Access table that might just do the
trick. Second, spreadsheets have more flexible parsing options than
databases. It may be possible to load the data into a spreadsheet. That
allows different algorithms to be applied to different rows.

Lastly, text files can be opened and read by VBA code in any of the
office languages, or any of the .NET languages. Either could be used,
but writing code to cope with all of the possible options may take time.

--
Bernard Peek
back in search of cognoscenti|||Erland Sommarskog (esquel@.sommarskog.se) writes:

Quote:

Originally Posted by

So a file could look like this:
>
2,34,Enter Sandman,Pat Boone
9,34,Zabadak,"Dave, Dee, Dozy, Mich & Tich"
8,981,"Rebel, Rebel",David Bowie
>
There is now way to get BULK INSERT to handle this file in that shape.
If I were faced with this file, I would write Perl script that replaced
the commas outside the "" with a different delimiter and then removed the
"". And it would not be trivial.


In addition to Bernard's post, is not Excel able to read that format?
In such case open in Except, and save as a tab-delimited file and importing
that should be a breeze. (Assuming, of course, there are no tabs in the
data!)

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Thank you both for your suggestions. Yes, I was thinking that BULK
INSERT was not going to be able to handle this. I had thought about
dumping the file into an Access table first, but the file could be very
large (200,000+ rows). I am going to try the Excel spreadsheet idea.

Erland Sommarskog wrote:

Quote:

Originally Posted by

Erland Sommarskog (esquel@.sommarskog.se) writes:

Quote:

Originally Posted by

So a file could look like this:

2,34,Enter Sandman,Pat Boone
9,34,Zabadak,"Dave, Dee, Dozy, Mich & Tich"
8,981,"Rebel, Rebel",David Bowie

There is now way to get BULK INSERT to handle this file in that shape.
If I were faced with this file, I would write Perl script that replaced
the commas outside the "" with a different delimiter and then removed the
"". And it would not be trivial.


>
In addition to Bernard's post, is not Excel able to read that format?
In such case open in Except, and save as a tab-delimited file and importing
that should be a breeze. (Assuming, of course, there are no tabs in the
data!)
>
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
>
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

|||(cabrenner@.optonline.net) writes:

Quote:

Originally Posted by

Thank you both for your suggestions. Yes, I was thinking that BULK
INSERT was not going to be able to handle this. I had thought about
dumping the file into an Access table first, but the file could be very
large (200,000+ rows). I am going to try the Excel spreadsheet idea.


200000+ rows? Then Access is probably a better bet. Doesn't Excel stop
at 65536 rows?

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Erland Sommarskog wrote:

Quote:

Originally Posted by

(cabrenner@.optonline.net) writes:

Quote:

Originally Posted by

>Thank you both for your suggestions. Yes, I was thinking that BULK
>INSERT was not going to be able to handle this. I had thought about
>dumping the file into an Access table first, but the file could be very
>large (200,000+ rows). I am going to try the Excel spreadsheet idea.


>
200000+ rows? Then Access is probably a better bet. Doesn't Excel stop
at 65536 rows?


I think the latest version of Excel may have a higher row limit - which
only increases the tendency of newbies to misuse Excel as a "database".|||You are correct - Excel has a limit on the number of rows. I thought
about that after I sent the reply. So now I am looking at Access.

Here is my next question. I want to use OPENROWSET in a procedure to
get the data from Access into SSE. My code looks something like this:

INSERT INTO sse_table1 Select GFF.*
FROM OPENROWSET(
'Microsoft.Jet.OLEDB.4.0',
'path to mdb';'admin';'',
'Select * FROM access_table1
) as GFF

This works great. However, the location of the access database is only
known at runtime. I can pass the path as a parameter to the stored
procedure, but using it as a variable in OPENROWSET fails. Code looks
like this

CREATE PROCEDURE [dbo].[spImportBillingFile]
@.strTableLocation varchar(255),
@.btSuccess bit OUTPUT
AS
BEGIN

DECLARE @.strConnect varchar(255)
SET @.strConnect = @.strTableLocation

INSERT INTO tbl_ups_eInvoice_tmpData Select GFF.*
FROM OPENROWSET(
'Microsoft.Jet.OLEDB.4.0',
' + @.strConnect + ';'admin';'',
'Select * FROM tbl_ups_eInvoice_tmpData'
) as GFF

Set @.btSuccess = 1

END

Does OPENROWSET not allow a variable to be used?

Thanks again for the help.

Ed Murphy wrote:

Quote:

Originally Posted by

Erland Sommarskog wrote:
>

Quote:

Originally Posted by

(cabrenner@.optonline.net) writes:

Quote:

Originally Posted by

Thank you both for your suggestions. Yes, I was thinking that BULK
INSERT was not going to be able to handle this. I had thought about
dumping the file into an Access table first, but the file could be very
large (200,000+ rows). I am going to try the Excel spreadsheet idea.


200000+ rows? Then Access is probably a better bet. Doesn't Excel stop
at 65536 rows?


>
I think the latest version of Excel may have a higher row limit - which
only increases the tendency of newbies to misuse Excel as a "database".

|||(cabrenner@.optonline.net) writes:

Quote:

Originally Posted by

INSERT INTO tbl_ups_eInvoice_tmpData Select GFF.*
FROM OPENROWSET(
'Microsoft.Jet.OLEDB.4.0',
' + @.strConnect + ';'admin';'',
'Select * FROM tbl_ups_eInvoice_tmpData'
) as GFF
>
Set @.btSuccess = 1
>
END
>
Does OPENROWSET not allow a variable to be used?


No. Either you have to use dynamic SQL, or define a linked server on the
fly. The former is probably simpler. Look at
http://www.sommarskog.se/dynamic_sql.html#OPENQUERY for a similar example
on how to deal with the nested strings.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Thanks for all the info - I figured out how to use the dynamic sql.

Erland Sommarskog wrote:

Quote:

Originally Posted by

(cabrenner@.optonline.net) writes:

Quote:

Originally Posted by

INSERT INTO tbl_ups_eInvoice_tmpData Select GFF.*
FROM OPENROWSET(
'Microsoft.Jet.OLEDB.4.0',
' + @.strConnect + ';'admin';'',
'Select * FROM tbl_ups_eInvoice_tmpData'
) as GFF

Set @.btSuccess = 1

END

Does OPENROWSET not allow a variable to be used?


>
No. Either you have to use dynamic SQL, or define a linked server on the
fly. The former is probably simpler. Look at
http://www.sommarskog.se/dynamic_sql.html#OPENQUERY for a similar example
on how to deal with the nested strings.
>
>
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
>
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

sql

Wednesday, March 21, 2012

Import excel file to SQL express

How do I Import excel file to SQL express

Do you mean you want to import the data from the Excel file, or store the Excel file itself in a BLOB field?

If the former, you can use the Jet 4.0 OLEDB provider to query Excel using SQL in exactly the same way as if it is an Access table. Select the data into a datatable, then export it to your Sql Server database.

|||I want to import the data from the Excel file to a Sql express database table|||Here's how to do it:http://davidhayden.com/blog/dave/archive/2006/05/31/2976.aspx|||

Hi Websta4,

Some additional information here, you can also use T-SQL script likes below:

SELECT*INTO myTableFROMOPENROWSET('Microsoft.Jet.OLEDB.4.0',

'Excel 8.0;Database=d:\test.xls', [Sheet1$])

You can run it directly in Management Studio or Copy the script in SqlCommand and execute it with NonQuery for .NET developing.

If you want to know any other way of importing data from Excel to SQL Server, I think this link is valuable.

http://support.microsoft.com/kb/321686

|||

I'm using SQL Server 2005 Express, SQL Server Management Studio Express and VWD 2005 Express, Excel 2003 and have tried your code above ie:

SELECT*INTO SomeTableFROMOPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=c:\test.xls', [Sheet1$])

but I get the error:

Msg 15281, Level 16, State 1, Line 1

SQL Server blocked access to STATEMENT 'OpenRowset/OpenDatasource' of component 'Ad Hoc Distributed Queries' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Ad Hoc Distributed Queries' by using sp_configure. For more information about enabling 'Ad Hoc Distributed Queries', see "Surface Area Configuration" in SQL Server Books Online.

Lost and confused. What does this mean? Is this the easiest way for importing Excel data into Sql Express for novices?

|||

This option is set to disabled bydefault you need to enable it from the Surface Area Configuration Menu in Programs>Sql Server 2005>configuration Tools>Sql Surface Area Configuration.

After the pop up will come select surface area configuration for features

Then it will open with a tree of feature.. for Clikc on AdHoc Queries Node and Enable the Check Box on right hand side

Let me know if you found any problem. But you should be admin to do that

|||

Satya, thank you!! That worked.

Question: When I run the SQL command I get an error saying the table already exists. For example: Let's say the Excel file gets updated every month. The first time you import he Excel data it will work fine. But the second time (and any other time), it will fail becuase it says the table already exists. Is there a parameter or switch or some other command to tell it to append the exisiting contents or overwrite the exisiting contents in the SQL Server Express database table?

Error:Msg 2714, Level 16, State 6, Line 1

There is already an object named 'SomeTable' in the database.

|||

THe simple way is to modify your query a bit like this

SELECT*INTO SomeTemp_TableFROMOPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=c:\test.xls', [Sheet1$])

INSERT INTO PERMANENT_TABLE

Select * from SomeTemp_Table

DROP TABLE SomeTemp_Table

-- where the PERMANENT_TABLE is your table in which each month you want to insert data

-- SomeTemp_Table is table a temporary one which will be used to to copy data from excel and then to your Permanent_Table

Cool Mark as answer if this helped you

sql

Monday, March 19, 2012

import database

I need to import a database from MS SQL 2000. I created the database. Then I create the database scripts and run them in sql express but I get this error.

"The specified schema name "username" either does not exist or you do not have permission to use it."

I have also tried to use DTS on MS SQL 2000 to export the data into text file. I do not have the ability to copy the mdf files and attach them in SQL express or make a backup.SQL Server introduced the schema whcih did not exist in SQL Server 200. YOu would either have to rename the object owner in the script to a existing schema (like dbo) or create the appropiate schemas in SQL Server 2005 which were fromer the owners of an object.

HTH, Jens K. Suessmeyer.

http://www.sqlserver2005.de|||

Hi,

Its self Explainatery message, it means that the Schema or User (Owner) does not exists on the system you are trying to run the script, create a similar user /change the schema in script . Do you have proper privilege !!!? Refer some link below, it will clear your doubts

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=176311&SiteID=1

http://msdn.microsoft.com/msdnmag/issues/05/06/SQLServerSecurity/

http://support.esri.com/index.cfm?fa=knowledgebase.techArticles.articleShow&d=30620

Hemantgiri S. Goswami

|||I made the schema change and it worked. Thanks.|||Thanks for the links it make a little more sense now.|||

Hi,

Thanks for the information, please click on Help full button if you feel answer is usefull.

Hemantgiri S. Goswami

Monday, March 12, 2012

Import data option not visible

Hello All,

I have created a database on my local machine using SQL Server Express 2005. I am trying to export data from an excel file into a table in this database but when i see tasks available for the database there is no option of import data like I assume there should.

Only the following options are visible.

Detach

Shrink

Back Up

Restore

Generate Scripts

Any solutions on how I can get my excel file into the table.

Kiran

Import / Export is not included in the Express edition.

http://www.microsoft.com/sql/prodinfo/features/compare-features.mspx

|||

Ohh.

Then would my only option be to download a different version like SQL Server compact.

Thanks,

Kiran

|||

Kiranvukkadala wrote:

Then would my only option be to download a different version like SQL Server compact.

No, only SQL Server Standard, Developer, or Enterprise editions. Read the link John provided.

|||

Would any of these editions be free to download from Microsoft. I need only a test database on my machine which uploads tables through excel files. If there is a workaround with express edition it would be great as I already downloaded that version.

Thanks,

Kiran

|||Nope. None are free. Sorry.

The developer edition is only $50 (US) though.

Import Data in SQL Server 2005?

I'm using SQL Server 2005 Management Studio Express, and trying to import data from an Excel spreadsheet into a new table. I'm used to doing this through Enterprise Manager in SQL Server 2000, but I'm not sure how to do it in the new interface. Is there a way to do a simple data import without also installing Business Intelligence Development Studio?

hi,

nope..

all this "stuff" has now be included in SSIS (integration service), not available in SSMSE as SQLExpress does not include the required runtime at all..

but you can perhaps interact with "linked servers" scenario and perform INSERT ... SELECT ...

something like http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=670748&SiteID=1

regards

|||Thank you!

Wednesday, March 7, 2012

Import and Export Data Wizard missing in SQL Server 2005 Express Edition

After some weeks evaluating tools and platforms for developing an application, I decided to move to SQL Server 2005 Express Edition. Everything was fine till last night, when after creating my tables, I needed to populate them. I tried to find the Import and Export Data Wizard that SQL Server 7.0 and 2000 used to have, but great was my surprise when I found - in this forum - a post that said that it's not available in the Express Edition.

I'll have to move back in time (what I hate) to remember the way BCP worked. Can somebody post some examples to not start from zero ? Does anybody know a third party visual tool that can import/export data from text files to a SQL Server DB via ODBC ?

What's the reason it was not included in the EE ?

THanks !

Hi,

BCP is documented in Books Online.

SQL Express is a free product and not all features are included. In this version they removed the Import/Export wizard for a number of reasons. We're looking at alternative soluitons for a future version of SQL Express.

Mike Wachal
SQL Express team

|||

Hi,

First off, please excuse the lack of specific detail but it's been a while since I installed this feature -

there is an import/export facility in SQL Server Express edition but it's in the "Advanced Features/Services" version.

You have to do a "custom" install and the import feature is buried in one of the tree feature diagrams and is NOT selected by default.

Open all the feature trees and check out the hints for each of the features to find the one you're after - it's definitely there 'cos I've used it to import data from an Excel workbook and from Access.

Really simple to use and very effective!

Best of luck!

|||

Hi Steve,

There is no supported Import/Export functionality in any version of SQL Express. Some people have managed to get the old Import/Export wizard onto their computers, but it has not been tested and it is not supported. If you go down this path, you do so at your own risk. BCP on the other hand is tested and supported.

Mike

|||

Steve,

thanks a lot for your coment. I'll give it a try if I don't succeed with BCP. My deadline is almost over and I can't make BCP work (I'm getting some memory allocation errors whn running it).

MIke,

do you have any other reference to BCP ? I need some working examples rather than the explanation of every parameter.

Other thing I need to know is how can I check the current version I have installed. Before starting this thread, I had just installed SQL Server 2005 Express Edition complete (with Managment Studio, Advanced Services and Toolkit). A couple of days ago, I noticed there was a SP2 and installed it over the older one and I generated an Hybrid that didn't work, so I removed all the installations (restarted) and then installed just SQL Server 2005 Express Edition and Management Studio (nothing else yet).

THanks !

|||

Go into Add/Remove Programs, find Microsoft SQL Server 2005 and click Change. When the wizard opens, there should be a Report button, clicking this will give you a report of everything you have installed and what version it is.

Try these references for using BCP:

http://support.microsoft.com/default.aspx/kb/67409
http://www.devarticles.com/c/a/SQL-Server/An-Introduction-To-The-Bulk-Copy-Utility/

Mike

|||

Mike,

thanks for letting me know the way to check version. I'll check the BCP links now.

Before getting this answer, I tried the following (I'm a bit desperate ):

Sent all the txt files to a friend and he imported to a SLQ Server 2k database and then he sent it back to me. After that, I ran the following in my SQL Server 2005 EE :

CREATE DATABASE Bolsa ON
(FILENAME = 'u:\Bolsa de Santiago\CD Bolsa\Bolsa_Data.MDF'),
(FILENAME = 'u:\Bolsa de Santiago\CD Bolsa\Bolsa_Log.ldf')
FOR ATTACH;
GO

and got this error.

Msg 3415, Level 16, State 1, Line 1
Database 'Bolsa' cannot be upgraded because it is read-only or has read-only files. Make the database or files writeable, and rerun recovery.

Any hint on how to fix it ?

Thanks !

|||

Not sure what the U: drive is for you, if that is actually the CD drive, you will need to copy the files to a different directory since CDs are read-only. If that is not yoru CD drive, try...

Take a look at the properties of the files (right-click | Properties) to see if they are set to Read-only.

One final note, SQL Express does not support attaching files from network locations or mapped drives, they have to be on the local hard drive. Again, just wondering about that U: drive.

Mike

|||

Mike,

before posting the above, I checked the files weren't Read Only and they are not in a CD (also no network here). U: drive for me is a 4GB NTFS partition from my master HDD. Could be a problem if it's not on a FAT32 drive ? I'm running Windows XP Home Edition SP2 (spanish) and SQL Server 2005 Express Edition SP2 (english).

Bye !

|||

The KB article at http://support.microsoft.com/kb/931640 suggests that this issue is actually caused by a setting on the files created on your friends SQL 2K server. It seems like you'll need to check the properties of the database server your friend used to create the files.

It might be faster to finish down the path of figuring out your BCP issues rather than start troubleshooting a completely different problem.

Mike

|||

Hi folks,

with all deference to your knowledge, Mike, I have DTS installed on my (newish) PC and have only ever installed SQL Express with Advanced Features and the Toolkit..

Admittedly, it took some finding, but there it is at "C:\Program Files\Microsoft SQL Server\90\Binn\DTS\DTSWizard.exe".

From a pragmatic point of view, with deadlines approaching, perhaps rrudolph should try (custom) installing the Toolkit and checking out ALL the component trees?

Regards to all

Steve

|||

Hi Steve,

I'm just telling you that using that wizard in Express has not been tested, nor is it supported, so you use it at your own risk.

The amount of work in a project is the sum of the work to do it the first time and then to do it over to fix your mistakes. I find using unsupported technology is usually one of those mistakes that needs to be fixed later.

Mike

|||

Mike,

the good news are that finally made the BCP work.

I have uploaded most of the data I needed. Just missing some files that when uploading them to the database, I noticed they contained had corrupted data. Thanks a lot for your helpful tips, links and directions. (hope next time I have to deal with BCP, I have no problems).

Steve,

I'm planning, after ending this project to re-install everything from scratch and then I will try to add the Wizard you mentioned. My doubt is last Thursday I started both installation programs ("SQL Server 2005 Express Edition with Advanced Services SP2" and "Microsoft SQL Server 2005 Express Edition Toolkit SP2") but canceled them before they modify my curent config. In none of them I was able to find the Import and Export Wizard you mentioned. I opened all the branches I found in the custom setup. When you installed yours, did you use the SP2 installation files (it's fresh from February 2007) or the ones from previous release ?

Thanks a lot !

|||

Rrudolph,

glad you got BCP running ok.

I'm still running SP1. I think(?) the wizard was in the Toolkit..!

However, if you have cracked the problems with BCP you might want to stick with that - as Mike correctly points out this DTS seems to be an un-supported feature (though why it should be so is a mystery).

I'm in the fortunate position of producing small, bespoke stuff where speed/ease of development is more important to my boss than anything else so can "risk" going with DTS (which, I'll admit, works for me like a dream).

OK, this doesn't seem to be full-blown DTS from SQL2000/2005 but it's sure good enough for my requirements.

Regards

Steve

ps - if you want me to find exactly where DTS was contact me and I'll re-install on my home PC to see where everything is.

|||

Steve,

thanks a lot for the offer.

I've just modified my profile to make my email addy visible. Email me to this one.

THanks !

Import and Export Data Wizard missing in SQL Server 2005 Express Edition

After some weeks evaluating tools and platforms for developing an application, I decided to move to SQL Server 2005 Express Edition. Everything was fine till last night, when after creating my tables, I needed to populate them. I tried to find the Import and Export Data Wizard that SQL Server 7.0 and 2000 used to have, but great was my surprise when I found - in this forum - a post that said that it's not available in the Express Edition.

I'll have to move back in time (what I hate) to remember the way BCP worked. Can somebody post some examples to not start from zero ? Does anybody know a third party visual tool that can import/export data from text files to a SQL Server DB via ODBC ?

What's the reason it was not included in the EE ?

THanks !

Hi,

BCP is documented in Books Online.

SQL Express is a free product and not all features are included. In this version they removed the Import/Export wizard for a number of reasons. We're looking at alternative soluitons for a future version of SQL Express.

Mike Wachal
SQL Express team

|||

Hi,

First off, please excuse the lack of specific detail but it's been a while since I installed this feature -

there is an import/export facility in SQL Server Express edition but it's in the "Advanced Features/Services" version.

You have to do a "custom" install and the import feature is buried in one of the tree feature diagrams and is NOT selected by default.

Open all the feature trees and check out the hints for each of the features to find the one you're after - it's definitely there 'cos I've used it to import data from an Excel workbook and from Access.

Really simple to use and very effective!

Best of luck!

|||

Hi Steve,

There is no supported Import/Export functionality in any version of SQL Express. Some people have managed to get the old Import/Export wizard onto their computers, but it has not been tested and it is not supported. If you go down this path, you do so at your own risk. BCP on the other hand is tested and supported.

Mike

|||

Steve,

thanks a lot for your coment. I'll give it a try if I don't succeed with BCP. My deadline is almost over and I can't make BCP work (I'm getting some memory allocation errors whn running it).

MIke,

do you have any other reference to BCP ? I need some working examples rather than the explanation of every parameter.

Other thing I need to know is how can I check the current version I have installed. Before starting this thread, I had just installed SQL Server 2005 Express Edition complete (with Managment Studio, Advanced Services and Toolkit). A couple of days ago, I noticed there was a SP2 and installed it over the older one and I generated an Hybrid that didn't work, so I removed all the installations (restarted) and then installed just SQL Server 2005 Express Edition and Management Studio (nothing else yet).

THanks !

|||

Go into Add/Remove Programs, find Microsoft SQL Server 2005 and click Change. When the wizard opens, there should be a Report button, clicking this will give you a report of everything you have installed and what version it is.

Try these references for using BCP:

http://support.microsoft.com/default.aspx/kb/67409
http://www.devarticles.com/c/a/SQL-Server/An-Introduction-To-The-Bulk-Copy-Utility/

Mike

|||

Mike,

thanks for letting me know the way to check version. I'll check the BCP links now.

Before getting this answer, I tried the following (I'm a bit desperate ):

Sent all the txt files to a friend and he imported to a SLQ Server 2k database and then he sent it back to me. After that, I ran the following in my SQL Server 2005 EE :

CREATE DATABASE Bolsa ON
(FILENAME = 'u:\Bolsa de Santiago\CD Bolsa\Bolsa_Data.MDF'),
(FILENAME = 'u:\Bolsa de Santiago\CD Bolsa\Bolsa_Log.ldf')
FOR ATTACH;
GO

and got this error.

Msg 3415, Level 16, State 1, Line 1
Database 'Bolsa' cannot be upgraded because it is read-only or has read-only files. Make the database or files writeable, and rerun recovery.

Any hint on how to fix it ?

Thanks !

|||

Not sure what the U: drive is for you, if that is actually the CD drive, you will need to copy the files to a different directory since CDs are read-only. If that is not yoru CD drive, try...

Take a look at the properties of the files (right-click | Properties) to see if they are set to Read-only.

One final note, SQL Express does not support attaching files from network locations or mapped drives, they have to be on the local hard drive. Again, just wondering about that U: drive.

Mike

|||

Mike,

before posting the above, I checked the files weren't Read Only and they are not in a CD (also no network here). U: drive for me is a 4GB NTFS partition from my master HDD. Could be a problem if it's not on a FAT32 drive ? I'm running Windows XP Home Edition SP2 (spanish) and SQL Server 2005 Express Edition SP2 (english).

Bye !

|||

The KB article at http://support.microsoft.com/kb/931640 suggests that this issue is actually caused by a setting on the files created on your friends SQL 2K server. It seems like you'll need to check the properties of the database server your friend used to create the files.

It might be faster to finish down the path of figuring out your BCP issues rather than start troubleshooting a completely different problem.

Mike

|||

Hi folks,

with all deference to your knowledge, Mike, I have DTS installed on my (newish) PC and have only ever installed SQL Express with Advanced Features and the Toolkit..

Admittedly, it took some finding, but there it is at "C:\Program Files\Microsoft SQL Server\90\Binn\DTS\DTSWizard.exe".

From a pragmatic point of view, with deadlines approaching, perhaps rrudolph should try (custom) installing the Toolkit and checking out ALL the component trees?

Regards to all

Steve

|||

Hi Steve,

I'm just telling you that using that wizard in Express has not been tested, nor is it supported, so you use it at your own risk.

The amount of work in a project is the sum of the work to do it the first time and then to do it over to fix your mistakes. I find using unsupported technology is usually one of those mistakes that needs to be fixed later.

Mike

|||

Mike,

the good news are that finally made the BCP work.

I have uploaded most of the data I needed. Just missing some files that when uploading them to the database, I noticed they contained had corrupted data. Thanks a lot for your helpful tips, links and directions. (hope next time I have to deal with BCP, I have no problems).

Steve,

I'm planning, after ending this project to re-install everything from scratch and then I will try to add the Wizard you mentioned. My doubt is last Thursday I started both installation programs ("SQL Server 2005 Express Edition with Advanced Services SP2" and "Microsoft SQL Server 2005 Express Edition Toolkit SP2") but canceled them before they modify my curent config. In none of them I was able to find the Import and Export Wizard you mentioned. I opened all the branches I found in the custom setup. When you installed yours, did you use the SP2 installation files (it's fresh from February 2007) or the ones from previous release ?

Thanks a lot !

|||

Rrudolph,

glad you got BCP running ok.

I'm still running SP1. I think(?) the wizard was in the Toolkit..!

However, if you have cracked the problems with BCP you might want to stick with that - as Mike correctly points out this DTS seems to be an un-supported feature (though why it should be so is a mystery).

I'm in the fortunate position of producing small, bespoke stuff where speed/ease of development is more important to my boss than anything else so can "risk" going with DTS (which, I'll admit, works for me like a dream).

OK, this doesn't seem to be full-blown DTS from SQL2000/2005 but it's sure good enough for my requirements.

Regards

Steve

ps - if you want me to find exactly where DTS was contact me and I'll re-install on my home PC to see where everything is.

|||

Steve,

thanks a lot for the offer.

I've just modified my profile to make my email addy visible. Email me to this one.

THanks !