Posts
83
Comments
600
Trackbacks
40
April 2005 Entries
Object Dependency Hierarchal Relationships

This always seems to pop as well.  To determine what objects are dependant on what you can use sp_depends.  Unfortunately that's for 1 level of relationships in either direction (to the parent or the child).  Also, and I don't know why they write them this way, but trying to automate some things using system stored procedures are a pain.  Especially when they return multiple result sets, or when the result have different number of columns.  At the bottom of this post is a rewrite of sp_depends that the script uses.  This script then builds a table of all the relationships in a database, and marries the object to it's dependants and parents.

It's then on to more trees and hierarchies written by Mr. Volk to mine the data.  But at least it's in a managable form now.

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_depends_xref ]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[sp_depends_xref ]
GO
CREATE TABLE sp_depends_xref (
   [name] nvarchar(128)
 , RefType char(2)
 , dep_name nvarchar(256)
 , type   char(16)
 , updated char(7)
 , selected char(8)
 , [column] nvarchar(128))
GO

DECLARE @name sysname, @MAX_name sysname, @sql varchar(8000), @xtype char(2)
SET NOCOUNT ON

  SELECT @name = MIN(name), @MAX_name = MAX(name)
    FROM sysobjects
   WHERE xtype <> 'S'

  SELECT @xtype = xtype FROM sysobjects WHERE [name] = @name


WHILE @name < @MAX_name
  BEGIN

 SELECT @name 


 SELECT @sql = 'INSERT INTO sp_depends_xref(reftype, dep_name, type, updated, selected,[column]) '
 + 'EXEC usp_depends2 [' + @name + ']'

 EXEC(@sql)
 UPDATE sp_depends_xref SET [name] = @name WHERE [name] IS NULL

   SELECT @name = MIN([name])
     FROM sysobjects
    WHERE xtype <> 'S'
      AND [name] > @name
  
   SELECT @xtype = xtype FROM sysobjects WHERE [name] = @name
  END


SELECT @sql = 'INSERT INTO sp_depends_xref(reftype, dep_name, type, updated, selected,[column]) '
+ 'EXEC usp_depends2 [' + @name + ']'

EXEC(@sql)
UPDATE sp_depends_xref SET [name] = @name WHERE [name] IS NULL
GO

SET NOCOUNT OFF
SELECT * FROM sp_depends_xref
GO

SET NOCOUNT OFF
GO


 


This is the rewite of sp_depends

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[usp_depends2]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[usp_Restore_Production]
 DROP PROC usp_depends2
GO

create procedure usp_depends2  --- 1996/08/09 16:51
@objname nvarchar(776)  /* the object we want to check */
as
declare @objid int   /* the id of the object we want */
declare @found_some bit   /* flag for dependencies found */
declare @dbname sysname

/*
**  Make sure the @objname is local to the current database.
*/


DECLARE @sp_depends_xref table (
   reftype char(2)
 , dep_name nvarchar(256)
 , type   char(16)
 , updated char(7)
 , selected char(8)
 , [column] nvarchar(128))


select @dbname = parsename(@objname,3)

if @dbname is not null and @dbname <> db_name()
 begin
  raiserror(15250,-1,-1)
  return (1)
 end

/*
**  See if @objname exists.
*/
select @objid = object_id(@objname)
if @objid is null
 begin
  select @dbname = db_name()
  raiserror(15009,-1,-1,@objname,@dbname)
  return (1)
 end

/*
**  Initialize @found_some to indicate that we haven't seen any dependencies.
*/
select @found_some = 0

set nocount on

/*
**  Print out the particulars about the local dependencies.
*/
if exists (select *
  from sysdepends
   where id = @objid)
begin
 raiserror(15459,-1,-1)
 INSERT INTO @sp_depends_xref (
    refType
  ,  dep_name
  , type
  , updated
  , selected
  , [column])
 select   'TO', 'name' = (s6.name+ '.' + o1.name),
    type = substring(v2.name, 5, 16),
    updated = substring(u4.name, 1, 7),
    selected = substring(w5.name, 1, 8),
             'column' = col_name(d3.depid, d3.depnumber)
  from  sysobjects  o1
   ,master.dbo.spt_values v2
   ,sysdepends  d3
   ,master.dbo.spt_values u4
   ,master.dbo.spt_values w5 --11667
   ,sysusers  s6
  where  o1.id = d3.depid
  and  o1.xtype = substring(v2.name,1,2) collate database_default and v2.type = 'O9T'
  and  u4.type = 'B' and u4.number = d3.resultobj
  and  w5.type = 'B' and w5.number = d3.readobj|d3.selall
  and  d3.id = @objid
  and  o1.uid = s6.uid
  and deptype < 2

 select @found_some = 1
end

/*
**  Now check for things that depend on the object.
*/
if exists (select *
  from sysdepends
   where depid = @objid)
begin
  raiserror(15460,-1,-1)
 INSERT INTO @sp_depends_xref (
    RefType
  , dep_name
  , type)
 select distinct 'BY', 'name' = (s.name + '.' + o.name),
  type = substring(v.name, 5, 16)
   from sysobjects o, master.dbo.spt_values v, sysdepends d,
    sysusers s
   where o.id = d.id
    and o.xtype = substring(v.name,1,2) collate database_default and v.type = 'O9T'
    and d.depid = @objid
    and o.uid = s.uid
    and deptype < 2

 select @found_some = 1
end

/*
**  Did we find anything in sysdepends?
*/
if @found_some = 0
 raiserror(15461,-1,-1)

 SELECT
    reftype
  , dep_name
  , type
  , updated
  , selected
  , [column]
 FROM @sp_depends_xref


set nocount off

 

return (0) -- sp_depends

 

posted @ Thursday, April 28, 2005 3:06 PM | Feedback (2)
TRUNCATE TABLE in DB2

Well there isn't one.  If you read this post and your platform is SQL Server or Oracle, I hope you feel very fortunate that you have

TRUNCATE TABLE <tablename>. 

It appears that in version 8, there is a callable procedure that is supplied by IBM, but it cannot be executed as a standard SQL command.  It probably not ANSI anyway.  In any event, the way of the world to do this in the past, to not incur heavy logging of a DELETE, was to use the DB2 Load utility and do a LOAD REPLACE.  This has the affect of marking the entire tablespace as emplty.  A tablespace is a set of predefined allocated space that may contain 1 or many tables.  It is very important to understand that a LOAD REPLACE will wipe out all tables in the TABLESPACE.  It is for this very reason that I traditionally will only allocate 1 table per tablespace.

I'll need to post the pain that's involved with stored procedures in DB2, but just as you can't call the TRUNCATE, you can't execute stored procedure at all, from SQL.  Then I stumbled on this link (after posting several times in DB2 Forums and getting no answer) I found this gem in the above link (written by Marina Greenstein (greenstm@us.ibm.com), Certified Consulting I/T Specialist - Data Management, IBM, Arthur V Sammartino (asamma@us.ibm.com), Certified Consulting I/T Specialist - Data Management, IBM and Knut Stolze (stolze@de.ibm.com), Information Integration Development, IBM)

UDF to call a stored procedure from a trigger or user-defined function

Another common issue encountered when migrating to DB2 is the capability of other RDBMS to call stored procedures from triggers or functions. Although this feature is available in DB2 UDB Version 8.2, earlier versions require a work-around. We show how this feature may be implemented using the version 7 or 8.1 of DB2; that is, by creating a UDF that will issue a call to a stored procedure.

OK, until I get around to writing an article the describes the PAIN involved in creating a stored procedures, please feel good about the platform you are on.  I will share the pain, and the tips to make your life easier in case you ever have to get invovled in creating DB2 Store Procedures.  But back to the article.

Here's the “Code“ to “TRUNCATE“ a table (well tablespace). it's actually called JCL (Job Control Language).

The steps that are executed are.

  1. Uncatalog any dataset names so the can be used by the job
  2. I unload the data prior to wiping it out
  3. Put the TABLESPACE in to UTILITY PENDING mode (So no one can access the tablespace while it's being worked on)
  4. LOAD The Table with the Control card using the Options LOAD DATA REPLACE...(Sample Card is at the bottom of the post).  The input Dataset used for the load is Dummied out.
  5. REPAIR The TABLESPACE
  6. Run RUNSTATS on the tablespace to update the system tables about the change to the TABLESPACEs Statistics
  7. Start the TABLESPACE and place it in Read Write Mode (RW) Mode

And that's it...pretty simple huh.

  

//REPLACE JOB (B,X,BB7200),'DB2 DBA',GROUP=AXBB72PA,          
//   NOTIFY=&SYSUID,MSGCLASS=V,COND=(4,LT),RESTART=STARTRW    
//*+JBS BIND XPDDBA1.ONLINE                                   
//UNCAT    EXEC PGM=IEXUNCAT,COND=(4,LT)                      
//SYSIN DD *                                                  
   BXBB72.DBA1.GUD000DA.UNLOAD.GUSBK011.D050428               
   BXBB72.X002548.DBA1.GUD000DA.DISC.GUSBK011                 
   BXBB72.X002548.DBA1.GUD000DA.UNLD.GUSBK011
                 
/*                                                            
//UNLOAD  EXEC PGM=IKJEFT01,REGION=6M,COND=(4,LT)             
//STEPLIB   DD DSN=AXXXA1.DB2.SDSNLOAD,DISP=SHR               
//SYSTSPRT  DD SYSOUT=*                                       
//SYSPRINT  DD SYSOUT=*                                       
//SYSUDUMP  DD DUMMY                                          
//SYSREC00  DD SPACE=(CYL,(100,25),RLSE),                     
//             UNIT=DASD,DISP=(,CATLG),LABEL=RETPD=365,       
//             DSN=BXBB72.DBA1.GUD000DA.UNLOAD.GUSBK011.D050428
//*SYSPUNCH  DD DUMMY                                         
//SYSPUNCH  DD DISP=SHR,                                            
//      DSN=BXBB72.X002548.DBA1.GUD000DA.CTLCRD(GUSBK011)           
//SYSTSIN   DD *                                                    
  DSN SYSTEM(DBA1)                                                  
  RUN PROGRAM(DSNTIAUL) PLAN(DSNTIAUL) -                            
      LIB('AXXXA1.DB2.RUNLIB.LOAD') PARMS('SQL')                    
  END
                                                               
/*                                                                  
//SYSIN DD DISP=SHR,DSN=BXBB72.X002548.DBA1.GUD000DA.UNLOAD(GUSBK011)
/*                                                                  
//STARTUT EXEC PGM=IKJEFT1A,DYNAMNBR=20                             
//STEPLIB  DD DSN=AXXXA1.DB2.SDSNLOAD,DISP=SHR                      
//SYSTSPRT DD SYSOUT=*                                              
//SYSPRINT DD SYSOUT=*                                              
//SYSUDUMP DD DUMMY                                                 
//SYSIN    DD DUMMY                                                 
//SYSTSIN  DD *                                                     
 DSN SYSTEM(DBA1)                                                   
 -START DATABASE(GUD000DA) SPACENAM(GUSBK011) ACCESS(UT)
            
/*                                                       
//LOAD     EXEC PGM=DSNUTILB,REGION=4096K,               
//         PARM='DBA1,GUSBK011'                          
//STEPLIB  DD DSN=AXXXA1.DB2.SDSNLOAD,DISP=SHR           
//SYSPRINT DD SYSOUT=*                                   
//UTPRINT  DD SYSOUT=*                                   
//SYSUDUMP DD DUMMY                                      
//SORTWK01 DD SPACE=(23476,(500,200),RLSE),UNIT=SYSOUT3  
//SORTWK02 DD SPACE=(23476,(500,200),RLSE),UNIT=SYSOUT3  
//SORTWK03 DD SPACE=(23476,(500,200),RLSE),UNIT=SYSOUT3  
//SORTWK04 DD SPACE=(23476,(500,200),RLSE),UNIT=SYSOUT3  
//SYSUT1   DD DSN=&&SYSUT1,DISP=(,PASS),UNIT=SYSOUT3,    
//            SPACE=(23476,(500,200),RLSE)               
//SORTOUT  DD DSN=&&SORTOUT,DISP=(,PASS),UNIT=SYSOUT3,   
//            SPACE=(23476,(500,200),RLSE)               
//SYSERR   DD DSN=&&SYSERR,DISP=(,PASS),UNIT=SYSOUT3,    
//            SPACE=(23476,(500,200),RLSE)               
//SYSMAP   DD DSN=&&SYSMAP,DISP=(,PASS),UNIT=SYSOUT3,    
//            SPACE=(23476,(500,200),RLSE)               
//SYSDISC  DD UNIT=DASD,DISP=(MOD,CATLG,CATLG),             
//         SPACE=(CYL,(100,25),RLSE),LABEL=RETPD=365,       
//         DSN=BXBB72.X002548.DBA1.GUD000DA.DISC.WPTA       
//SYSREC00 DD DUMMY                                         
//*SYSREC00 DD DISP=SHR,                                    
//*         DSN=BXBB72.X002548.DBA1.GUD000DA.DATA.WPTA      
//*        DSN=BXBB72.X002548.DBB1.GUD000DA.DATA.REQ001     
//*        DSN=BXBB72.X002548.DBA1.GUD000DA.WPTA.D020205    
//SYSIN    DD DISP=SHR,                                     
//         DSN=BXBB72.X002548.DBA1.GUD000DA.CTLCRD(GUSBK011)
//*                                                         
//* REPAIR                                                  
//*                                                         
//REPAIR   EXEC PGM=DSNUTILB,REGION=4096K,COND=(4,LT),      
//    PARM='DBA1,GUSBK011'                                  
//STEPLIB  DD DSN=AXXXA1.DB2.SDSNLOAD,DISP=SHR              
//SYSPRINT DD SYSOUT=*                                      
//UTPRINT  DD SYSOUT=*                                      
//SYSUDUMP DD SYSOUT=*                                      
//SYSIN    DD *                                                
 REPAIR OBJECT SET TABLESPACE GUD000DA.GUSBK011 NOCOPYPEND     
//*                                                            
//**************************************************************
//* REORG                                                      
//*                                                            
//* RUNSTAT                                                    
//*                                                            
//RUNSTAT EXEC DSNUPROC,SYSTEM=DBA1,UID='GUSBK011',UTPROC=''   
//STEPLIB  DD DSN=AXXXA1.DB2.SDSNLOAD,DISP=SHR                 
//SYSPRINT DD SYSOUT=*                                         
//UTPRINT  DD SYSOUT=*                                         
//SYSUDUMP DD DUMMY                                            
//DSNUPROC.SYSIN    DD  *                                      
RUNSTATS TABLESPACE GUD000DA.GUSBK011 INDEX(ALL) SHRLEVEL CHANGE
//*                                                            
//* RESTART TABLESPACE                                         
//*                                                            
//STARTRW EXEC PGM=IKJEFT1A,DYNAMNBR=20,COND=(4,LT)            
//STEPLIB  DD DSN=AXXXA1.DB2.SDSNLOAD,DISP=SHR           
//SYSTSPRT DD SYSOUT=*                                   
//SYSPRINT DD SYSOUT=*                                   
//SYSUDUMP DD DUMMY                                      
//SYSIN    DD DUMMY                                      
//SYSTSIN  DD *                                          
 DSN SYSTEM(DBA1)                                        
 -START DATABASE(GUD000DA) SPACENAM(GUSBK011) ACCESS(RW)
 
/*                                                       


Sample Load Card

  LOAD DATA REPLACE LOG NO INDDN SYSREC00 INTO TABLE                
      AXBB72DA.WS_SERV_LOG                                          
   (                                                                
   LOGIN_ID                               POSITION(       1         )
   CHAR(                     30) ,                                  
   HOST_IP                                POSITION(      31         )
   CHAR(                     20) ,                                  
   REQ_URL                                POSITION(      51         )
   CHAR(                    100) ,                                  
   QUERY_STRING                           POSITION(     151         )
   CHAR(                    100) ,                                  
   REQ_DOMAIN                             POSITION(     251         )
   CHAR(                    100) ,                                  
   REQ_TS                                 POSITION(     351         )
   TIMESTAMP EXTERNAL(       26) ,                                  
   REQ_PROC                               POSITION(     377         )
   CHAR(                      8) ,                                  
   REQ_RS                                 POSITION(     385         )
   INTEGER                       ,                                   
   REQ_LENGTH                             POSITION(     389:     397)
   DECIMAL                       ,                                   
   SQLCODE                                POSITION(     398         )
   INTEGER                                                           
   )                                                                 

posted @ Thursday, April 28, 2005 11:54 AM | Feedback (6)
Error = [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'DESC'.

bcp fails to import data near reserved word.

[Doooh]Alrighty then.  Thanks Tara (again) for pointing out the obvious.  The resolution to this problem is the -q option.  As BOL states, it sets quoted identifiers on in the context of the bcp thread.  So that solves that problem, and I'm sure it's one that I won't forget.  It's curious why there isn't a problem with the bcp out though.[/Doooh]

BOL

-q

Executes the SET QUOTED_IDENTIFIERS ON statement in the connection between the bcp utility and an instance of SQL Server. Use this option to specify a database, owner, table, or view name that contains a space or a quotation mark. Enclose the entire three-part table or view name in double quotation marks (" ").

Who knew?  OK, probably everyone.  I have never run into this before (mostly because I don't use reserve words as column names).  The work around I used was to create a view.  If anyone has a slicker way, or better, an explanation as to why bcp does fail, I'm all ears...or is that eyes?  In any case....something for future reference so I don't have to remember it, and hopefully someone else might benefit.

USE Northwind
GO

SET NOCOUNT ON
CREATE TABLE myTable99(Col1 int, [DESC] varchar(8000))
GO

INSERT INTO myTable99 (Col1, [DESC])
SELECT 1, 'I' UNION ALL
SELECT 2, 'Me' UNION ALL
SELECT 3, 'Mine'
GO

SELECT * FROM myTable99

EXEC master..xp_cmdshell 'bcp Northwind.dbo.myTable99 out d:\data\Northwind_dbo_myTable99.dat -Usa -P -S -c'
GO

TRUNCATE TABLE myTable99
GO

EXEC master..xp_cmdshell 'bcp Northwind.dbo.myTable99 in d:\data\Northwind_dbo_myTable99.dat -Usa -P -S -c -q'
GO

SELECT * FROM myTable99
GO

CREATE VIEW myView99
AS
SELECT Col1,  [DESC] AS Col2 FROM myTable99
GO

EXEC master..xp_cmdshell 'bcp Northwind.dbo.myView99 in d:\data\Northwind_dbo_myTable99.dat -Usa -P -S -c'
GO

SELECT * FROM myTable99
GO

SET NOCOUNT OFF
DROP VIEW myView99
DROP TABLE myTable99
GO

 

posted @ Monday, April 25, 2005 9:04 AM | Feedback (10)
CREATE TYPE2 UNIQUE WHERE NULL INDEX

This pops up every so often, as it does Here.  The post title is the DB2 syntax for achieving a unique index that allows for nulls.  I always felt that since Nulls are not equal to anything, not even themselves, then how could you get a dup key violation.   To be fair, even in DB2 you can not have a primary key that allows more than 1 Null.  But you can create a unique index in lieu of the the PK that will allow nulls.  This allows the ability to build non-identifying relationships, something I believe is lacking in SQL Server. 

In any event, there are all kinds of work arounds to do this, as David shows here.  Also, with my exposure to SQL Server, it is the general concensus to avoid nulls at all cost.  I was raised differently.  After reading Bonnie Bakers article, “Much Ado about Nulls” I am convinved more now than ever (well, ok, that was about 5 years ago).

Anyway, here's a method using a trigger where you can simulate this.

Update:  I forgot to add code to handle the update...duh.  The additional code is added in Purple for anyone who has already downloaded the code.  Or you can just cut and paste it all over.

Note:  With the new code added for the update, it's kind of a hack, since I'm using the identity column.  What I should really do, instead of using the surrogate, is to perform a logical update to the natural keys(Col1 and Col2) by performing a DELETE and a new INSERT operation.  This eliminates the dependancy on the surrogate.  But as an example, it serves it's purpose here.  Thanks for reading.

USE Northwind
GO

SET NOCOUNT ON
CREATE TABLE
myTable99 (
 [id] int IDENTITY (1, 1) NOT NULL ,
 Col1 varchar (15) NULL ,
 Col2 varchar (14) NULL ,
)


CREATE INDEX myTable99_Col1 ON myTable99(Col1)
CREATE INDEX myTable99_Col2 ON myTable99(Col2)
GO

CREATE TRIGGER myTrigger99 ON myTable99
INSTEAD OF INSERT, UPDATE
AS
  BEGIN

 SET NOCOUNT ON
 IF
EXISTS ( SELECT *
        FROM myTable99 t
  INNER JOIN inserted i
          ON t.Col1 = i.Col1
         AND t.Col2 = i.Col2
       WHERE i.Col1 IS NOT NULL
         AND i.Col2 IS NOT NULL)
 OR EXISTS ( SELECT *
        FROM myTable99 t
  INNER JOIN inserted i
          ON t.Col1 = i.Col1
       WHERE i.Col1 IS NOT NULL
         AND i.Col2 IS NULL AND t.Col2 IS NULL)
 OR EXISTS ( SELECT *
        FROM myTable99 t
  INNER JOIN inserted i
   ON t.Col2 = i.Col2
       WHERE i.Col1 IS NULL AND t.Col1 IS NULL
         AND i.Col2 IS NOT NULL)
   BEGIN
  RAISERROR
('Violation of Logical PRIMARY KEY constraint. Cannot insert duplicate key in object myTest99', 16, 1)
     ROLLBACK TRANSACTION
   END
 ELSE IF EXISTS(SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted)
  INSERT INTO myTable99(Col1, Col2) SELECT Col1, Col2 FROM inserted
 ELSE
  UPDATE t
     SET Col1=i.Col1
       , Col2=i.Col2
    FROM myTable99 t INNER JOIN inserted i
      ON t.[id] = i.[id]


 SET NOCOUNT OFF
  END

GO


INSERT INTO myTable99(Col1, Col2)
SELECT '1' , Null UNION ALL
SELECT '1' , '1'  UNION ALL
SELECT Null, '1'  UNION ALL
SELECT '2' , '2'  UNION ALL
SELECT '2' , Null UNION ALL
SELECT Null, '2'  UNION ALL
SELECT Null, '3'  UNION ALL
SELECT '3' , Null UNION ALL
SELECT '3' , '3'
GO

SELECT * FROM myTable99
GO

UPDATE myTable99 SET Col1 = 4 WHERE id = 9

UPDATE myTable99 SET Col2 = 4 WHERE id = 9

SELECT * FROM myTable99
GO

--Dup Keys

INSERT INTO myTable99(Col1, Col2)
SELECT '1', Null
GO

INSERT INTO myTable99(Col1, Col2)
SELECT '1', '1'
GO

INSERT INTO myTable99(Col1, Col2)
SELECT Null, '1'
GO

UPDATE myTable99 SET Col2 = 4 WHERE id = 9
GO

SET NOCOUNT OFF
DROP TRIGGER
myTrigger99
DROP TABLE myTable99
GO

posted @ Wednesday, April 20, 2005 1:23 PM | Feedback (3)
DTS too hard to export data (How to export a table with a header using bcp)

I swear that's what was posted.  Mostly they want a header row in their data and they didn't want to use DTS...

bcp out with column names post

OK, here you go..probably need to deal with more datatype than I have accounted for...

USE Northwind
GO

SET NOCOUNT ON

DECLARE @sql1 varchar(8000), @sql2 varchar(8000), @TABLE_NAME sysname, @TABLE_SCHEMA sysname

DECLARE myCursor99 CURSOR
  FOR
 SELECT TABLE_SCHEMA, TABLE_NAME
   FROM INFORMATION_SCHEMA.Tables
  WHERE TABLE_TYPE = 'BASE TABLE'
    AND TABLE_NAME LIKE 'O%'

OPEN myCursor99
FETCH NEXT FROM myCursor99 INTO @TABLE_SCHEMA, @TABLE_NAME

WHILE @@FETCH_STATUS = 0
  BEGIN

 SELECT @sql2 = ' UNION ALL SELECT ', @sql1 = null
 
 SELECT @sql1 = COALESCE(@sql1 + ', '+''''+'"'+''''+'+'+'''','') + COLUMN_NAME + ''''+'+'+''''+'"'+''''+' AS '+ COLUMN_NAME
   FROM INFORMATION_SCHEMA.Columns
  WHERE TABLE_NAME = @TABLE_NAME
    AND TABLE_SCHEMA = @TABLE_SCHEMA
 
 SELECT @sql2 = CASE
       WHEN DATA_TYPE IN ('datetime','smalldatetime')
       THEN @sql2 + ', '+''''+'"'+''''+'+CONVERT(varchar(24),' + COLUMN_NAME + ',126)+' + ''''+ '"' + '''' + 'AS ' + COLUMN_NAME
       WHEN DATA_TYPE IN ('bigint','int','smallint','tinyint','money','float','real')
       THEN @sql2 + ', '+''''+'"'+''''+'+CONVERT(varchar(15),' + COLUMN_NAME + ')+' + ''''+ '"' + '''' + 'AS ' + COLUMN_NAME
       WHEN DATA_TYPE IN ('char','varchar','nchar','nvarchar')
       THEN @sql2 + ', '+''''+'"'+''''+'+' + COLUMN_NAME + '+' + ''''+ '"' + '''' + 'AS ' + COLUMN_NAME
         END
   FROM INFORMATION_SCHEMA.Columns
  WHERE TABLE_NAME = @TABLE_NAME
    AND TABLE_SCHEMA = @TABLE_SCHEMA
 
 SELECT @sql1 = 'CREATE VIEW ' + REPLACE('['+@TABLE_SCHEMA+'].[v_'+@TABLE_NAME+'_99]',' ','_')
   + ' AS SELECT '+''''+'"'+''''+'+'+''''
   + @sql1 + REPLACE(@sql2,'UNION ALL SELECT ,','UNION ALL SELECT ')
   + ' FROM ['+@TABLE_SCHEMA+'].['+@TABLE_NAME+']'
 
 SELECT @sql1
 
 EXEC(@sql1)
 
-- SELECT * FROM myView99
 
 DECLARE @cmd varchar(8000)
 
 SELECT @cmd = 'bcp ' + db_name() + '.' + REPLACE('['+@TABLE_SCHEMA+'].[v_'+@TABLE_NAME+'_99] ',' ','_')
   +' OUT '
   +REPLACE(@TABLE_SCHEMA+'_'+@TABLE_NAME,' ','_')
   +'_hdr.txt -c -S -Usa -P'
 SELECT @cmd 
 EXEC master..xp_cmdshell @cmd
 
 SELECT @sql2 = 'DROP VIEW ' + REPLACE('['+@TABLE_SCHEMA+'].[v_'+@TABLE_NAME+'_99]',' ','_')
 EXEC(@sql2)

 FETCH NEXT FROM myCursor99 INTO @TABLE_SCHEMA, @TABLE_NAME
  END
CLOSE myCursor99
DEALLOCATE myCursor99
GO

posted @ Wednesday, April 13, 2005 3:07 PM | Feedback (3)