Advertisement
kavallo

Leer archivo como tabla - uftReadfileAsTable

Dec 19th, 2014
371
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 2.11 KB | None | 0 0
  1. https://www.simple-talk.com/SQL/t-sql-programming/reading-and-writing-files-in-sql-server-using-t-SQL/
  2.  
  3.  
  4.  
  5. CREATE FUNCTION [dbo].[uftReadfileAsTable]
  6. (
  7. @Path VARCHAR(255),
  8. @Filename VARCHAR(100)
  9. )
  10. RETURNS
  11. @File TABLE
  12. (
  13. [LineNo] INT IDENTITY(1,1),
  14. line VARCHAR(8000))
  15.  
  16. AS
  17. BEGIN
  18.  
  19. DECLARE  @objFileSystem INT
  20.         ,@objTextStream INT,
  21.         @objErrorObject INT,
  22.         @strErrorMessage VARCHAR(1000),
  23.         @Command VARCHAR(1000),
  24.         @hr INT,
  25.         @String VARCHAR(8000),
  26.         @YesOrNo INT
  27.  
  28. SELECT @strErrorMessage='opening the File System Object'
  29. EXECUTE @hr = sp_OACreate  'Scripting.FileSystemObject' , @objFileSystem OUT
  30.  
  31.  
  32. IF @HR=0 SELECT @objErrorObject=@objFileSystem, @strErrorMessage='Opening file "'+@path+'\'+@filename+'"',@command=@path+'\'+@filename
  33.  
  34. if @HR=0 execute @hr = sp_OAMethod   @objFileSystem  , 'OpenTextFile'
  35.     , @objTextStream OUT, @command,1,false,0--for reading, FormatASCII
  36.  
  37. WHILE @hr=0
  38.     BEGIN
  39.     if @HR=0 Select @objErrorObject=@objTextStream,
  40.         @strErrorMessage='finding out if there is more to read in "'+@filename+'"'
  41.     if @HR=0 execute @hr = sp_OAGetProperty @objTextStream, 'AtEndOfStream', @YesOrNo OUTPUT
  42.  
  43.     IF @YesOrNo<>0  break
  44.     if @HR=0 Select @objErrorObject=@objTextStream,
  45.         @strErrorMessage='reading from the output file "'+@filename+'"'
  46.     if @HR=0 execute @hr = sp_OAMethod  @objTextStream, 'Readline', @String OUTPUT
  47.     INSERT INTO @file(line) SELECT @String
  48.     END
  49.  
  50. if @HR=0 Select @objErrorObject=@objTextStream,
  51.     @strErrorMessage='closing the output file "'+@filename+'"'
  52. if @HR=0 execute @hr = sp_OAMethod  @objTextStream, 'Close'
  53.  
  54.  
  55. if @hr<>0
  56.     begin
  57.     Declare
  58.         @Source varchar(255),
  59.         @Description Varchar(255),
  60.         @Helpfile Varchar(255),
  61.         @HelpID int
  62.    
  63.     EXECUTE sp_OAGetErrorInfo  @objErrorObject,
  64.         @source output,@Description output,@Helpfile output,@HelpID output
  65.     Select @strErrorMessage='Error whilst '
  66.             +coalesce(@strErrorMessage,'doing something')
  67.             +', '+coalesce(@Description,'')
  68.     insert into @File(line) select @strErrorMessage
  69.     end
  70. EXECUTE  sp_OADestroy @objTextStream
  71.     -- Fill the table variable with the rows for your result set
  72.    
  73.     RETURN
  74. END
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement