Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

Thursday, March 29, 2012

Executing SQL Statement from flat file

I have been attempting to load a SQL Server table by extracting data from Oracle using a parameterized query. I need to retrieve the Oracle data from views where the key equals a specific value. The values are based on data from other Oracle tables.

I was able to create a file that contains 1 row for each key value in the syntax of "select .... from viewname where key = value". I'd like to be able to loop through the file, execute each statement, and load the resultant row(s) into a SQL Server table.

I looked at the ForEach container, but it appears to only list the files in a directory. I thought I was on the right track using the Execute SQL Task, but I could not figure out how to get the data loaded into SQL.

Any help would be greatly appreicated. Consider me an SSIS novice.

Thanks

I'm not sure if this is a good idea, but how about this?

A script task which will read the entire contents of the file and assign it to an object variable.
This object variable should be of array type, if you can iterate through the array in the for loop to execute your sql statements from the array.

Thanks|||

Another thought: If the source for your keys is a database, you can use an Execute SQL Task to get a list of keys into a recordset, and the ForEach (set to ADO Recordset instead of directory) to iterate through it.

To get the data loaded, you should use a data flow task with an OLEDB Source pointed to Oracle, and an OLEDB Destination pointed to SQL Server. The source should be set to get it's SQL from a variable (which should be populated with your view select statement).

Here's a similar example (one of many, if you search around you'll find more): http://agilebi.com/cs/blogs/jwelch/archive/2007/03/20/using-for-each-to-iterate-a-resultset.aspx

|||

I was able to get the expected data loaded into SQL Server.

thanks for the help

Executing SQL Statement from flat file

I have been attempting to load a SQL Server table by extracting data from Oracle using a parameterized query. I need to retrieve the Oracle data from views where the key equals a specific value. The values are based on data from other Oracle tables.

I was able to create a file that contains 1 row for each key value in the syntax of "select .... from viewname where key = value". I'd like to be able to loop through the file, execute each statement, and load the resultant row(s) into a SQL Server table.

I looked at the ForEach container, but it appears to only list the files in a directory. I thought I was on the right track using the Execute SQL Task, but I could not figure out how to get the data loaded into SQL.

Any help would be greatly appreicated. Consider me an SSIS novice.

Thanks

I'm not sure if this is a good idea, but how about this?

A script task which will read the entire contents of the file and assign it to an object variable.
This object variable should be of array type, if you can iterate through the array in the for loop to execute your sql statements from the array.

Thanks|||

Another thought: If the source for your keys is a database, you can use an Execute SQL Task to get a list of keys into a recordset, and the ForEach (set to ADO Recordset instead of directory) to iterate through it.

To get the data loaded, you should use a data flow task with an OLEDB Source pointed to Oracle, and an OLEDB Destination pointed to SQL Server. The source should be set to get it's SQL from a variable (which should be populated with your view select statement).

Here's a similar example (one of many, if you search around you'll find more): http://agilebi.com/cs/blogs/jwelch/archive/2007/03/20/using-for-each-to-iterate-a-resultset.aspx

|||

I was able to get the expected data loaded into SQL Server.

thanks for the help

Executing SQL scripts from files

Hi, I want to create many files with SQL statements and then I want to write one SQL script file, which executes SQL statement in the other files. How can I do it?

Thanks, Radco

You could do it with Stored Procedures - create a bunch of them - then create one last one, which will execute the others.

If this doesn't do what you want - maybe you could explain your scenario in more detail

|||No it is not what I wanted. I can say to it, that I have a very long script which creates a database for testing, It has more than 2100 lines of SQL statements (mostly INSERT). It begins to be hardly manageable. So I want to split this one script into many files to simplify it. If I want to change something now I need to search 2100 lines of code. If I split it I will only change one smaller file.|||

It is rather not possible to read SQL statement from file and run on SQL server using T-SQL, but you can create your files and next merge them together and run final one. or you can write simple VB application which will read your query and execute them on SQL server.

You can also try to use command line SQL tool osql to run your queries from inside dos batch file.

Thanks

Executing sql scripts from aspx....plz Help!

Hi All,
How to execute the sql scripts (which may be in .sql file or a string) from code behind files?

Thanx
Veeru.SqlCommand.ExecuteNonQuery()

The only problem I can think of is that .SQL scripts generated by Query Analyzer often have the 'GO' keyword in them, which is not a SQL keyword, but rather used for batching in QA.|||True, going to have to parse out GO statement. Some more things needed

SqlCommand comm = New SqlCommand("select * from table", sqlConnection)
comm.CommandType = CommandType.Textsql

executing sql file

I want to know,

is there any method in SQL Server using "SQL Server Management Studio" to execute the .sql file? (Using query)

I know about osql & isql Utilities & i try this also as

EXEC xp_cmdshell 'osql -S vsnet1 -U sa -P sysadm -d aaa -i c:\ACCOUNTS.sql'

its working fine but it uses the dos command shell.

i too try the stored procedures (of others peson`s) like

sp_ExecuteSQLFromFile (i dont want this as it having some limits)

Is there any direct way to execute a .sql file? (as in case of Oracle RUN, START, @. )

Hope for help

Regards,

thanks.

Gurpreet S. Gill

I don't think Management studio provides any other way of executing the .sql file.

The most common way is to use sqlcmd from cmd prompt...

type in

sqlcmd /? from command prompt for more help

|||

Imtiaz--

I cant use the DOS prompt. i know about these commands like sqlcmd, isql, osq

but i want from SQL Server Managment

Regards,

Thanks.

Gurpreet S. Gill

|||

This sounds like it might help you out... you can enable "SQLCMD mode" in SQL Server Management Studio.

Steps:

1) Open SQL Server Management Studio.
2) Open a query window
3) Click the Query menu
4) Click SQLCMD Mode.

Kimberly Tripp does some great demos with SQLCMD. Not sure if it's on a webcast you can watch OnDemand though. Here are some BOL articles you can read.

Editing SQLCMD Scripts with Query Editor
http://msdn2.microsoft.com/en-us/library/ms174187.aspx

SQLCMD Mode
http://msdn2.microsoft.com/en-us/library/ms170411.aspx

Paul A. Mestemaker II
Program Manager
Microsoft SQL Server Manageability
http://blogs.msdn.com/sqlrem/

|||

Paul--

Thanks

that`s really gr8.

This is what i want.

Regards,

Thanks.

Gurpreet S. Gill

Executing SP From a Batch file

I was wondering how I can create a batch file that call a store procedure an
d
put the output on a file.Silver wrote:
> I was wondering how I can create a batch file that call a store
> procedure and put the output on a file.
Try osql.exe - the command-line options are documented in Books Online or by
typing osql /? at the command line.
John.|||Hi,
Call OSQL inside the command prompt
Entries inside the batch file will be
OSQL -Usa -Ppassword -S Servername -d Dbname -Qprocedurename -oc:\output.log
Thanks
Hari
SQL Server MVP
"Silver" <Silver@.discussions.microsoft.com> wrote in message
news:341FE12A-19E6-4A8B-8003-558797A637BF@.microsoft.com...
>I was wondering how I can create a batch file that call a store procedure
>and
> put the output on a file.

Executing Script Files From Transact-SQL

Hi,

I have my create statments for tables, procedures, views, etc in
individual Transact-SQL script files (.sql).

I wnat to write another script file that executes these scripts in the
correct order to create the database.

What is the syntax for executing script files from Transact-SQL?

Thanks, PhilPhil (hp_howell@.hotmail.com) writes:
> I have my create statments for tables, procedures, views, etc in
> individual Transact-SQL script files (.sql).
> I wnat to write another script file that executes these scripts in the
> correct order to create the database.
> What is the syntax for executing script files from Transact-SQL?

There isn't one really. Once the batch has been sent to SQL Server,
the script is executing on the server and not on the machine where you
have the scripts.

You can, though, use xp_cmdshell to fork out and run a script through a
command-line tool like OSQL. Beware then that you are running from a second
connection.

Another alternative is to run the scripts with OSQL from the client machine,
and use ~r to include files. Note that ~r is a command to OSQL, and is not
understood by Query Analyzer or SQL Server.

My personal preference for install scripts is to run them in some client
language (Perl in my case). This does not have to be advanced. Basically
just something which reads the files, passes it to SQL Server through some
API call or through OSQL, and then maybe checks for errors.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.aspsql

executing querys from a batch file

Someone asked me a curious question.

Can I execute a query to sql server from a bat file? how?

If not is there a simple scripting laguage that this person might use to
drive his process that is similar to a dos bat file?William Kossack (kossackw@.njc.org) writes:
> Someone asked me a curious question.
> Can I execute a query to sql server from a bat file? how?
> If not is there a simple scripting laguage that this person might use to
> drive his process that is similar to a dos bat file?

You can use the command-line tool OSQL for this.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Can you point me to an example or somewhere to look online?

Erland Sommarskog wrote:

>William Kossack (kossackw@.njc.org) writes:
>
>>Someone asked me a curious question.
>>
>>Can I execute a query to sql server from a bat file? how?
>>
>>If not is there a simple scripting laguage that this person might use to
>>drive his process that is similar to a dos bat file?
>>
>>
>You can use the command-line tool OSQL for this.
>
>|||http://msdn.microsoft.com/library/d...mta_01_5zxi.asp

--
----------
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland

IM: mike@.epprecht.net

MVP Program: http://www.microsoft.com/mvp

Blog: http://www.msmvps.com/epprecht/

"William Kossack" <kossackw@.njc.org> wrote in message
news:11fktjioc9cp78d@.corp.supernews.com...
> Can you point me to an example or somewhere to look online?
> Erland Sommarskog wrote:
>>William Kossack (kossackw@.njc.org) writes:
>>
>>>Someone asked me a curious question.
>>>Can I execute a query to sql server from a bat file? how?
>>>
>>>If not is there a simple scripting laguage that this person might use to
>>>drive his process that is similar to a dos bat file?
>>>
>>
>>You can use the command-line tool OSQL for this.
>>
>>
>>
>|||and
http://msdn.microsoft.com/library/d...mta_01_2q61.asp

--
----------
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland

IM: mike@.epprecht.net

MVP Program: http://www.microsoft.com/mvp

Blog: http://www.msmvps.com/epprecht/

"William Kossack" <kossackw@.njc.org> wrote in message
news:11fktjioc9cp78d@.corp.supernews.com...
> Can you point me to an example or somewhere to look online?
> Erland Sommarskog wrote:
>>William Kossack (kossackw@.njc.org) writes:
>>
>>>Someone asked me a curious question.
>>>Can I execute a query to sql server from a bat file? how?
>>>
>>>If not is there a simple scripting laguage that this person might use to
>>>drive his process that is similar to a dos bat file?
>>>
>>
>>You can use the command-line tool OSQL for this.
>>
>>
>>
>|||For an example how to embed a SQL script within a batch script so that you end up with only one file look here:

http://dostips.cmdtips.com/DtCodeInterfacing.php

Tuesday, March 27, 2012

Executing osql commands through batch file

Hello

I have a script ,which runs with osql

The script is :

osql -E
declare @.cmd nvarchar(1000)
declare @.cmd2 nvarchar(1000)
declare @.state1 varchar(100)
declare @.message varchar(100)
set @.message = ''
-- Build command to determine state of SQLSERVERAGENT service on Master Server
SET @.CMD = 'create table #state (state varchar(2000))' + char(10) +
'declare @.cmdx varchar(1000)' + char(10) +
'insert into #state EXEC master..xp_servicecontrol ''''QueryState'''', ''''SQLSERVERAGENT'' +
+ char(10) + 'select @.state=state from #state' + char(10) +
'drop table #state'
-- Build command to execute command that determines state of service being monitored
set @.cmd2 = 'declare @.state varchar(100)' + char(10) +
'exec ' + rtrim(@.@.servername) + '.master.dbo.sp_executesql N''' + @.CMD + ''',' +
'N''@.state varchar(100) out'',' +
'@.state out' + char(10) +
'set @.state1 = @.state'
-- Execute command and return state of service being monitored
exec master.dbo.sp_executesql @.cmd2,N'@.state1 varchar(100) out',@.state1 out
-- Is the service that was monitored not
IF (UPPER(@.state1) <> 'RUNNING.')
--if @.state1 <1 'Running.'
begin
-- Display message that primary monitor is down
select @.message = @.message+char(13)+ @.@.servername + ' -' + 'Sql Server Agent Not Running'+char(13)
print 'Master server "' + rtrim(@.@.servername) + '" for monitoring is not available.'
exec master.dbo.xp_smtp_sendmail

It works fine when I run it on the command line prompt.
And I receive a mail , if the server agent is running.

But when I save it as bat file and try to run , it stops and doesnot even give an error.

Can anyone let me know what I can do.

ThanksHello

I have got it working.

Just I need to use :

osql -E -iC:\serveragent.sql -oC:\outputfile.txt

Thanks

executing one .sql file from another

I need to run a x.sql fil from another y.sql file. The y.sql file is executed by OSQL.
I can't find out if it is posible or not. I triet using EXEC but that doesn't work.if you create each as stored procedures, you can exec them from eachother...otherwise (though it is a terrible habit and not recommended) you can use xp_CMDShell

Executing Multi-lines SQL Scripts From Command-line

Hello,

I'm trying to execute a file containing few SQL statements.

CREATE VIEW test1 AS SELECT * FROM table1;
CREATE VIEW test2 AS SELECT * FROM table2;

The standard SQL way is to end a statement with semi-colon.
But doing that,it doesn't work in SQL Server.
After changing ";" to "GO", it works fine.

Is there anyway we can stick to ";" to indicate the end of statement.
I don't want to create scripts which works only in SQL Server.

Please comment.

Thanks in advance.Simon Hayes (sql@.hayes.ch) writes:
> Neither the semi-colon nor GO are 'standard' SQL. GO is recognized by the
> SQL Server client tools as a batch delimiter. The semi-colon is the Oracle
> equivalent, as far as I know.

And the ANSI equivalent. Hey, have you never seen Joe Celko's postings?
He has semi-colons all over the place.

Semicolon as a statement terminator is indeed standard SQL, and it is a
pity that Sybase way back in the 1980s settled on a semicolon-free syntax.
Microsoft added semicolons as a optional terminator in SQL7, but it would
constitute a major blow to existing code to make it mandatory. (But if
MS would supply a tool that added all missing semicolons to existing
code, it could be worth the effort.)

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||James (ehchn1@.hotmail.com) writes:
> I'm trying to execute a file containing few SQL statements.
> CREATE VIEW test1 AS SELECT * FROM table1;
> CREATE VIEW test2 AS SELECT * FROM table2;
> The standard SQL way is to end a statement with semi-colon.
> But doing that,it doesn't work in SQL Server.
> After changing ";" to "GO", it works fine.
> Is there anyway we can stick to ";" to indicate the end of statement.
> I don't want to create scripts which works only in SQL Server.

This is not legal T-SQL:

CREATE VIEW test1 AS SELECT * FROM table1;
go
CREATE VIEW test2 AS SELECT * FROM table2;
go

For some explicable reason ; is not permitted here. (Probably because
CREATE VIEW must be alone in a batch.

However, if you change the batch separator to with the -c option as
Simon Hayes suggested, this works:

CREATE VIEW test1 AS SELECT * FROM table1
;
CREATE VIEW test2 AS SELECT * FROM table2
;

And it still legal in ANSI-compliant engines.

Since the batch-separator must be alone on a line, this solution
can work decently. Of course if a developer for some reason puts a
lone semicolon in the middle of a stored procedure, he effectively
splits that procedure in two.
--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||"Erland Sommarskog" <sommar@.algonet.se> wrote in message
news:Xns93D3E36904A63Yazorman@.127.0.0.1...
> Simon Hayes (sql@.hayes.ch) writes:
> > Neither the semi-colon nor GO are 'standard' SQL. GO is recognized by
the
> > SQL Server client tools as a batch delimiter. The semi-colon is the
Oracle
> > equivalent, as far as I know.
> And the ANSI equivalent. Hey, have you never seen Joe Celko's postings?
> He has semi-colons all over the place.
> Semicolon as a statement terminator is indeed standard SQL, and it is a
> pity that Sybase way back in the 1980s settled on a semicolon-free syntax.
> Microsoft added semicolons as a optional terminator in SQL7, but it would
> constitute a major blow to existing code to make it mandatory. (But if
> MS would supply a tool that added all missing semicolons to existing
> code, it could be worth the effort.)
> --
> Erland Sommarskog, SQL Server MVP, sommar@.algonet.se
> Books Online for SQL Server SP3 at
> http://www.microsoft.com/sql/techin.../2000/books.asp

Interesting, I didn't know there was any standard at all in that area. It's
a good point about Celko's posts, though, given his insistence on
platform-independent code - I guess I should have worked that one out...

Simon

Monday, March 26, 2012

Executing commands in parallel

I have the need to run multiple SQL commands (like osql and bcp) in parallel
from a single bat file. To describe this a little clearer...
While executing a single .BAT file, I want to be able to execute 3 OSQL
commands in parallel. Currently I have to run these 3 serially and it takes
too long.
Is there any way from within a single bat file that I could have 3 OSQL
commands running at the same time?
Thanks in advance."TJT" <T_homas.T_odd@.smed.com> wrote in message
news:OHrmXephDHA.604@.TK2MSFTNGP10.phx.gbl...
> I have the need to run multiple SQL commands (like osql and bcp) in
parallel
> from a single bat file. To describe this a little clearer...
> While executing a single .BAT file, I want to be able to execute 3 OSQL
> commands in parallel. Currently I have to run these 3 serially and it
takes
> too long.
> Is there any way from within a single bat file that I could have 3 OSQL
> commands running at the same time?
>
start osql.exe . . .
start osql.exe . . .
start osql.exe . . .
From a command prompt type
start /?
for help with the start command.
Davidsql

Executing BCP from C# code

Aloha to all,
I have thrown together some code that generates a file with a lot of
data (something like 200,000 rows). I would like to load all this data
in a SQL Server table, but my attempt to execute BCP from C# doesn't
want to behave.
I do as follows (more of less stealing everything from
http://dotnetjunkies.com/WebLog/ste...8/19/22566.aspx
):
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = false;
proc.StartInfo = new System.Diagnostics.ProcessStartInfo();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.FileName = "bcp";
proc.StartInfo.Arguments = @."DATABASE_NAME.dbo.TABLE_NAME in
c:\inetpub\wwwroot\project\bcpData.txt -c -Uusername -Ppassword -t','
-Sservername";
proc.EnableRaisingEvents = true;
proc.Start();
string s1 = proc.StandardOutput.ReadLine();
string s2 = proc.StandardOutput.ReadLine();
All I get from this code is:
s1 = "SQLState = 28000, NativeError = 18456";
s2 = "Error = [Microsoft][SQL Native Client][SQL Server]Login failed
for user 'username'."
I have off course checked the username/password a thousand times and it
is correct. If I copy my Arguments string to the command prompt, I can
execute BCP without any problem
Thank you and roger over, MadsYou could try creating a batch file and then run that. It seems like it's
having trouble putting the arguments in correctly. I don't have the time
right now to try compiling and running your code... but I'm sure you could
easily throw the whole line into a file and running it.
Security-wise though, I'd consider using a trusted connection and
impersonating a particular user.
Unfortunately my timezone means I'm about to go offline for a while, so I
can't post a follow-up. Someone else will though I'm sure (and they'll
probably tell you to ignore me!)
Rob
"Mads.phi@.gmail.com" wrote:

> Aloha to all,
> I have thrown together some code that generates a file with a lot of
> data (something like 200,000 rows). I would like to load all this data
> in a SQL Server table, but my attempt to execute BCP from C# doesn't
> want to behave.
> I do as follows (more of less stealing everything from
> http://dotnetjunkies.com/WebLog/ste...8/19/22566.aspx
> ):
> System.Diagnostics.Process proc = new System.Diagnostics.Process();
> proc.EnableRaisingEvents = false;
> proc.StartInfo = new System.Diagnostics.ProcessStartInfo();
> proc.StartInfo.UseShellExecute = false;
> proc.StartInfo.RedirectStandardOutput = true;
> proc.StartInfo.RedirectStandardError = true;
> proc.StartInfo.FileName = "bcp";
> proc.StartInfo.Arguments = @."DATABASE_NAME.dbo.TABLE_NAME in
> c:\inetpub\wwwroot\project\bcpData.txt -c -Uusername -Ppassword -t','
> -Sservername";
> proc.EnableRaisingEvents = true;
> proc.Start();
> string s1 = proc.StandardOutput.ReadLine();
> string s2 = proc.StandardOutput.ReadLine();
> All I get from this code is:
> s1 = "SQLState = 28000, NativeError = 18456";
> s2 = "Error = [Microsoft][SQL Native Client][SQL Server]Login failed
> for user 'username'."
> I have off course checked the username/password a thousand times and it
> is correct. If I copy my Arguments string to the command prompt, I can
> execute BCP without any problem
> Thank you and roger over, Mads
>|||Excellent! That fixed my problems, so the only thing left is that I'm
ashamed of not having thought of a .bat file myself.
Thank you, Mads|||About the C# code, in general I'd change
proc.StandardOutput.ReadLine();
to
proc.StandardOutput.ReadToEnd();
to grab all the error message for troubleshooting purposes. Of course, this
doesn't address your particular problem.
Linchi
"Mads.phi@.gmail.com" wrote:

> Excellent! That fixed my problems, so the only thing left is that I'm
> ashamed of not having thought of a .bat file myself.
> Thank you, Mads
>

Executing an external process() in SQLCLR Project

I can create an external text file from within the SQLCLR project, but I cannot run an external executable. Just in case you are asking, I need to do this to push data into a legacy application using a different DB format. I have found it best to simply use my old language (Clipper) for data validation, etc. - and especially since I require multiple indices to be open. So, if you could just take my word on this.

The following code:

Process newProcess = new Process();

string path = @."C:\TEST.BAT";

newProcess.StartInfo.FileName = path;

newProcess.Start();

Executes without error, but does not actually run the external.

Now, I can have a DOS (Clipper) application poll a directory for text files, but I am trying to get away from all these "mini" data transformation applications. If an exception is caused in the DOS app, a remote user on the other side of the country has no idea it is broke and his data (coming from a SQL Mobile Device) never gets to our legacy database structure.

So, am I out of luck?

Is your assembly deployed at the UNSAFE permission level? What happens if you try to run the same code in a console app run under the same user account (SQL Server service account or impersonated account, as appropriate)?|||

Hi Nicole - thx for responding.

I am able to execute a console app - the issue is that SQL Server will not allow touching any network drive or network resource period (from a SQLCLR Project). So my cmd app can update a DB on the C drive, but not one of my network drives.

As well, I can establish an OLEDB connection (Visual Foxpro) to a local directory, but not a network directory. I'm surprised that CLR will not even allow an external app to touch a network resource. Wild, eh? Although I understand why there is such security, there must be a way for me to execute an external console app that can update a DB on a network resource.

Oh - and yes, I am running the assembly at the UNSAFE permission level.

|||Might the problem be the user context rather than anything having to do with SQLCLR? Unless you deliberately impersonate another user (e.g.: via SqlContext.WindowsIdentity.Impersonate), your SQLCLR code will run under the user context of the SQL Server service account, which is highly unlikely to have any permissions on any network resources.|||

I think you're correct - it has to do with attempting to authenticate a local user (IUSR_Computername) on a network resource. I will look into impersonation (something my wife says I'm horrible at...)

You know, Nicole, you are the first person to assist me in these forums. I had actually thought of using a female handle - seems they get a pretty quick response... :)

I'll post the results of my efforts... and thx again.

|||

After impersonation, I can do something simple like use a streamwriter to create a text file on a network share. But it still throws an exception when attempting to execute an executable on the same network share. The impersonation rights are those of administrator (only for testing!). Oh, in case you're wondering - I simply change the Process StartInfo from @."C:\Mobile.exe" to @."F:\Mobile.exe", and you will have to take my word for it that the Mobile exists in both places. It runs without exception on the C drive.

What's really wild, is that the actual Mobile.exe code (clipper) will update a dbf on the C drive, but not on the F drive. What does the CLR do? Freeze all resources when in process? geez!

I'm also using:

[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]

So... I really thought this would allow my CLR code to access a network share. I can't understand why the answer to this wouldn't be just a little more simple, even for an old programmer like me.

Executing an application from a query

Hi All,
Is it possible to execute a file or perhaps send a call to a
webpage using an SQL query? Does anyone know of any such feature.
Basically I need to call a webpage(coldfusion script) from my query and
I am wondering if anyone knows of any way that his would be possible.
Thanks a heap in advance for all your help !
Harkirat>> Is it possible to execute a file or perhaps send a call to a webpage
Can you be more specific? SQL Queries are executed on the server while web
pages are displayed on the client. So what exactly do you mean by "calling"
a webpage? Are you trying to display the webpage on the client or somewhere
else? SQL Server has some provisions for generating web pages based on
generated resultsets, but I am not sure that is what you are looking for.
Anith|||Hi Anith,
What I need to do is be able to execute a coldfusion script
via a query. The script can be run via a webpage e.g.
http://mysite.com/CFScript.cfm
So if I could make a 'call' to my webpage via my query that would work.
Also if this is not a possibility would it be possible to execute a
.exe file using a query? That might help too.
Thanks for your reply.
Harkirat
Anith Sen wrote:
> Can you be more specific? SQL Queries are executed on the server while web
> pages are displayed on the client. So what exactly do you mean by "calling
"
> a webpage? Are you trying to display the webpage on the client or somewher
e
> else? SQL Server has some provisions for generating web pages based on
> generated resultsets, but I am not sure that is what you are looking for.
> --
> Anith|||You can use a stored procedure to execute an .exe file using
xp_cmdshell, but there are security issues. I don't think that it;s
the best approach to what you are trying to do, however; what does a
cold fusion script have to do with your data?
Can you provide a little more detail about the business problem you're
trying to solve, and perhaps we can suggest a better alternative.
Stu|||Hi Stu,
My coldfusion script has logic that
updates a table in the database. I need this process to run everytime a
new row is inserted in my table. Hence I was thinking of putting an
insert trigger that calls this coldfusion script.
Can you give an example on how to execute a .exe using a stored
procedure. I could perhaps make a .exe that executes the coldfusion
script which in turn would be called via my trigger.
Thanks.
Harkirat|||Hi
Look at xp_cmdshell in BOL.
If your exe fails, the insert will get rolled back as an error like that can
not be handled in T-SQL. It is not a good idea. Rather write a row in a
queue table, and have something poll the table and then call your exe.
Regards
--
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland
IM: mike@.epprecht.net
MVP Program: http://www.microsoft.com/mvp
Blog: http://www.msmvps.com/epprecht/
"harry" <i1073@.tamu.edu> wrote in message
news:1124657414.378047.144430@.g44g2000cwa.googlegroups.com...
> Hi Stu,
> My coldfusion script has logic that
> updates a table in the database. I need this process to run everytime a
> new row is inserted in my table. Hence I was thinking of putting an
> insert trigger that calls this coldfusion script.
> Can you give an example on how to execute a .exe using a stored
> procedure. I could perhaps make a .exe that executes the coldfusion
> script which in turn would be called via my trigger.
> Thanks.
> Harkirat
>|||I think your application would perform better if you could keep the
database logic at the dataase level; if it were me, I would probably
simply run the logic in T-SQL as part of the trigger. Why bubble back
up (unless of course your coldfusion script is extremely complicated)?
As for an example, I don't write many triggers, and I disable
xp_cmdshell altogether. Books OnLine is your best bet.
Stu|||Hi Stu,
My coldfusion is indeed complicated thats why I don't wish
to do it in SQL.
Thanks for your help.
Harkirat|||Hi Mike,
I had already thought of that. Seems like my best bet
now.
Thanks for your help.
Harkirat

Friday, March 23, 2012

executing a package with dtexec.exe

Hi,
when I run the following from the command prompt I am getting an error saying that can not set the variable Status as int.

dtexec /File "C:\work\SSIS Packages\Dataflow\ControlRoom.dtsx" /SET

\Package.Variables[ChannelCode].Value;"test" /SET

\Package.Variables[Status].Value;1

both variables as you can see are in the top level.
the problem is that ChannelCode is string but Status is Integer.
if I take out the /SET \Package.Variables[Status].Value;1 part from the command line it will work fine. I think th eproblem is down to diffenrt types of variable as there are two types of String and Interger.

any ideas on what the problem migth be.
p.s. I am runnning SQL server 2005 Dev edition (without any SP)
CheersAre you sure [Status] is an integer in your package?

What happens when you run it with:
/SET \Package.Variables[Status].Value;"1"|||yes it is Integer and don't want to change it to string as I have ament that in few places in my package|||Have you tried DTexecUI to set those values and see how the command line gets generated?|||this is what get's generated

/FILE "C:\work\SSIS Packages\Dataflow\ControlRoom.dtsx" /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING EW /SET "\Package.Variables[ChannelCode].Value";Test /SET "\Package.Variables[Status].Value";1
but I'm getting the same problem
back to square one|||Can you please post the exact error?|||I'm getting

Started: 4:56:31 PM
Error: 2007-03-26 16:56:33.37
Code: 0xC0017006
Source: ControlRoom
Description: The expression "@.Status == 1" must evaluate to True or False. Ch
ange the expression to evaluate to a Boolean value.
End Error
Error: 2007-03-26 16:56:33.37
Code: 0xC0014021
Source: ControlRoom

as it does a check against the Status value that I'm loading from the command prompt.
if I specify (hardcode) the variable value inside the package it will work fine, this happens only when I try to pass the value from command prompt
Thanks|||Do you have EvaluateAsExpression set to false when you need to have it set to true somewhere?

I don't think we have all of the pieces of the puzzle here, but it seems that "@.Status == 1" is being passed in as a string, not a conditional check.|||sorry, I think it's my fault as I didn't plain a clear picture.
I am passing the variable Status from command prompt and inside the package it trys to check if the passes value is 1
as the Status value is not getting passed from the command prompt and the default value of @.Status in the package is to 0, the condition fails.

now if I hardcode the default value of @.status in the package to 1 and do not try to pass the value for status from command prompt. it work perfectly!
I hope this makes it clear|||And the scope of the variable is correct? You don't have two variables of the same name in different scopes, do you? This can happen.

For instance, you could have a Status variable of package scope and have a Status variable of data flow scope in the same package.|||I thought that this might be the issue but I'm looking at all the variables across the whole package and there isn't any other one with the same name. @.Status is the only and as you can see it is at the top level so it is visible by all the sub tasks.
cheers|||

Kolf wrote:

I thought that this might be the issue but I'm looking at all the variables across the whole package and there isn't any other one with the same name. @.Status is the only and as you can see it is at the top level so it is visible by all the sub tasks.
cheers

Yep, I can see that, but just because it's visible to subtasks doesn't mean that the subtasks can't have their own variable of the same name, that's why I asked.|||

Kolf wrote:

... and inside the package it trys to check if the passes value is 1 ...

How are you doing this? Where are you doing this? Control flow, data flow, conditional split, derived column, etc...|||in the varaible windows I click on a button called show user variable and that displays all the variables define with in that package and I have just one variable called @.Status which is Int32
Thanks

Executing A File In Sql Query Analyzer

I Had A Text File In Which There Are Sqlstatements.i Want To Execute The Entire File In Query Analyzer.what Command I Must Use For That?

Quote:

Originally Posted by megastar5

I Had A Text File In Which There Are Sqlstatements.i Want To Execute The Entire File In Query Analyzer.what Command I Must Use For That?


Open the file in Query Analyzer, then hit F5.

Wednesday, March 21, 2012

Executing .sql file using SMO

Hi all,

Is it possible to execute a .sql file using SMO. like in old days we used to use osql.exe to execute the sql files

Thanks in advance

Rujith

Hi,

you don′t need SMO for that,executing scripts can be done via a *normal* sqlconnection (untested script, just wroite down in notepad)

static void Main(string[] args)
{

if (args[0] == null)
{
Console.WriteLine("No file passed to the program.");
return;
}

if (!File.Exists(args[0].ToString()))
{
Console.WriteLine("File does not exist.");
return;
}

try
{
FileStream file = new FileStream(args[0].ToString(), FileMode, FileAccess);
StreamReader sr = new StreamReader(file);
string Commands = sr.ReadToEnd();
sr.Close();
file.Close();

SqlCommand cmd = new SqlCommand(Commands);
cmd.Connection.ConnectionString = "Data Source=.;Integrated Authentication=true";
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Exeception occured: {0}", ex.Message));
}

}

HTH, Jens Suessmeyer.

|||

Hi

This code exevuted for some .sql file

but not for all .

how to do that ?

?

|||

Hi,

what do you mean by *all* ?

-Jens.

|||

I mean

that i do have some script file

One for TAble

One for View

One for Stored procedures and so on...

I also have developed same type of code.

But this code runs for only that table script file only

but not for othres;

specially

Code gives error where GO command is there in script;

|||Either replace the GOs in the script or slit the string into a string array which can be executed one by one.

HTH, Jens Suessmeyer.

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

Also check out ExecuteNonQuery function:

server.ConnectionContext.ExecuteNonQuery(sqlStatements);

This function "understands" GO batch separators. You would of course need to load the text from a file to a string.

Artur Laksberg
SQL Server Team
Microsoft

|||

Thnx Artur laksberg

but u have not mentioned what is this "server" object.

please tell about class to which this object does belongs to.

Waiting for yor reply

uday (Emersion)

|||Hi ermersion,
take a look inte namespace

Microsoft.SqlServer.Management.Smo
There is a server class which hold the method Arthur was talking about.
The namespace can be used by referencing the assembly directly (installed in the GAC) or by a file reference on
Microsoft.SqlServer.Smo.dll
SomeTime Ago, I created a small app for a user mapping, the server class is also used there, perhaps you can get a feeling from this:
http://www.sqlserver2005.de/SharedFiles/UserMappingwithSMO.zip
HTH, Jens Suessmeyer.

http://www.sqlserver2005.de

|||

Artur laksberg MSFT wrote:

Also check out ExecuteNonQuery function:

server.ConnectionContext.ExecuteNonQuery(sqlStatements);

This function "understands" GO batch separators. You would of course need to load the text from a file to a string.

Artur Laksberg
SQL Server Team
Microsoft

That's what we did. It read the script line by line. When GO was encountered, it submitted what was accumulated to SQL Server using an ADO SQL command object ExecuteNonQuery method. It works fine.

Not familiar with the object you're talking about. We'll have to check that out because it would be more effecient to send scripts that contain multiple batches. However, that requires our customers to upgrade to SQL 2005 (or install the add-on's) to get SMO.

Joe

Executing .sql file using SMO

Hi all,

Is it possible to execute a .sql file using SMO. like in old days we used to use osql.exe to execute the sql files

Thanks in advance

Rujith

Hi,

you don′t need SMO for that,executing scripts can be done via a *normal* sqlconnection (untested script, just wroite down in notepad)

static void Main(string[] args)
{

if (args[0] == null)
{
Console.WriteLine("No file passed to the program.");
return;
}

if (!File.Exists(args[0].ToString()))
{
Console.WriteLine("File does not exist.");
return;
}

try
{
FileStream file = new FileStream(args[0].ToString(), FileMode, FileAccess);
StreamReader sr = new StreamReader(file);
string Commands = sr.ReadToEnd();
sr.Close();
file.Close();

SqlCommand cmd = new SqlCommand(Commands);
cmd.Connection.ConnectionString = "Data Source=.;Integrated Authentication=true";
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Exeception occured: {0}", ex.Message));
}

}

HTH, Jens Suessmeyer.

|||

Hi

This code exevuted for some .sql file

but not for all .

how to do that ?

?

|||

Hi,

what do you mean by *all* ?

-Jens.

|||

I mean

that i do have some script file

One for TAble

One for View

One for Stored procedures and so on...

I also have developed same type of code.

But this code runs for only that table script file only

but not for othres;

specially

Code gives error where GO command is there in script;

|||Either replace the GOs in the script or slit the string into a string array which can be executed one by one.

HTH, Jens Suessmeyer.

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

Also check out ExecuteNonQuery function:

server.ConnectionContext.ExecuteNonQuery(sqlStatements);

This function "understands" GO batch separators. You would of course need to load the text from a file to a string.

Artur Laksberg
SQL Server Team
Microsoft

|||

Thnx Artur laksberg

but u have not mentioned what is this "server" object.

please tell about class to which this object does belongs to.

Waiting for yor reply

uday (Emersion)

|||Hi ermersion,
take a look inte namespace

Microsoft.SqlServer.Management.Smo
There is a server class which hold the method Arthur was talking about.
The namespace can be used by referencing the assembly directly (installed in the GAC) or by a file reference on
Microsoft.SqlServer.Smo.dll
SomeTime Ago, I created a small app for a user mapping, the server class is also used there, perhaps you can get a feeling from this:
http://www.sqlserver2005.de/SharedFiles/UserMappingwithSMO.zip
HTH, Jens Suessmeyer.

http://www.sqlserver2005.de

|||

Artur laksberg MSFT wrote:

Also check out ExecuteNonQuery function:

server.ConnectionContext.ExecuteNonQuery(sqlStatements);

This function "understands" GO batch separators. You would of course need to load the text from a file to a string.

Artur Laksberg
SQL Server Team
Microsoft

That's what we did. It read the script line by line. When GO was encountered, it submitted what was accumulated to SQL Server using an ADO SQL command object ExecuteNonQuery method. It works fine.

Not familiar with the object you're talking about. We'll have to check that out because it would be more effecient to send scripts that contain multiple batches. However, that requires our customers to upgrade to SQL 2005 (or install the add-on's) to get SMO.

Joe

Executing .sql file using in .NET

Hello,

I want to execute .sql files against my database in c#.

please Help me.

Hi,

funny thing, I posted that this week in the SMO group:

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

HTH, Jens Suessmeyer.

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

Hello, Jens

Yes i know that you have posted that .

but i have replied it problem of that code

bcoz i had written same kind of code.

http://forums.microsoft.com/MSDN/showpost.aspx?postid=323013&siteid=1

Uday

|||Do you want to execute more than one file in a directory ? Or what do you want to achieve ?

HTH, Jens Suessmeyer.

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

I assume this is the problem you are referring to:

"Code gives error where GO command is there in script;".

A SqlCommand string cannot contain the "GO" command. If you remove the lines containing the "GO" commands you should be fine.

|||

Thanks peter for reply

I have already tried script removeing "GO" but still it is not working.

actually i have generated script files by system(SQL Sever Enterprise Manager) itself.

|||

Jens Thanks for Reply

I have .sql file generated by SQL Server Enterprise manager.

i want to execute this file. but it does not.

Then i have generate .sql file for each object separately.

now file table.sql (for tables only) runs correctly,

but for view (view.sql) doesnot run properly.

in all case error is same

"Create view must be first line in Query Batch."

Now what to do ?

Waiting for Your Reply

Emersion

|||

Ok, did you try to serparate the string object you are getting back from reading from the file by splitting it into a string array and executing each string in the string array ?

Thats the think which comes up in mind for this problem.

Jens.

|||

Or you can split the file .sql file into multiple files at the lines where the "GO" commands were originally.