Unix Technical Forum

How can I use variables in this TSQL Statement

This is a discussion on How can I use variables in this TSQL Statement within the SQL Server forums, part of the Microsoft SQL Server category; --> Hi all, I would like to replace the default directory location (c:\temp) and the filename (emails.csv) with variables like ...


Go Back   Unix Technical Forum > Database Server Software > Microsoft SQL Server > SQL Server

FAQ Members List Calendar Search Today's Posts Mark Forums Read
  #1 (permalink)  
Old 03-04-2008, 07:23 AM
Greg Hines
 
Posts: n/a
Default How can I use variables in this TSQL Statement

Hi all,

I would like to replace the default directory location (c:\temp) and the
filename (emails.csv) with variables like @FileDir and @FileName in the
statement below.

SELECT @cnt = COUNT(*) FROM OpenRowset('MSDASQL', 'Driver={Microsoft Text
Driver (*.txt; *.csv)}; DefaultDir=c:\temp;','select * from "emails.csv"')

However, my attempts have not been successful.

Any ideas appreciated, and TIA.

Greg


Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #2 (permalink)  
Old 03-04-2008, 07:23 AM
Plamen Ratchev
 
Posts: n/a
Default Re: How can I use variables in this TSQL Statement

OPENROWSET does not accept variables for its arguments and you have to use
dynamic SQL. It may look like this:

DECLARE @FileDir NVARCHAR(80);
DECLARE @FileName NVARCHAR(80);
DECLARE @sql NVARCHAR(500);
DECLARE @params NVARCHAR(50);
DECLARE @cnt INT;

SET @FileDir = N'C:\Temp';
SET @FileName = N'emails.csv';
SET @params = N'@cnt_out INT OUTPUT';

SET @sql =
N'SELECT @cnt_out = COUNT(*)
FROM OPENROWSET(''MSDASQL'',
''Driver={Microsoft Text Driver (*.txt; *.csv)}; DefaultDir= ' + @FileDir +
''', ''SELECT * FROM ' + @FileName + ''');';

EXEC sp_executesql @sql, @params, @cnt_out=@cnt OUTPUT;
SELECT @cnt;

HTH,

Plamen Ratchev
http://www.SQLStudio.com

Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 03-04-2008, 07:23 AM
Greg Hines
 
Posts: n/a
Default Re: How can I use variables in this TSQL Statement

Many thanks, works like a dream.


Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump


All times are GMT. The time now is 01:45 PM.


Powered by vBulletin® Version 3.6.5
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.2.0
www.UnixAdminTalk.com