- Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathSQLTableOrViewToJSON.sql
More file actions
Latest commit
505 lines (375 loc) · 17.9 KB
/
Copy pathSQLTableOrViewToJSON.sql
File metadata and controls
505 lines (375 loc) · 17.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
--USE Temp
IFOBJECT_ID('dbo.SQLTableOrViewToJSON') ISNULL-- Check if SP Exists
EXEC('CREATE PROCEDURE dbo.SQLTableOrViewToJSON AS SET NOCOUNT ON;') -- Create dummy/empty SP
GO
ALTERPROCEDURE SQLTableOrViewToJSON
@TableName VARCHAR(MAX) ='',
@ExportPath VARCHAR(MAX) ='',
@ExportName VARCHAR(MAX) =''
AS
BEGIN--BEGIN OF STORED PROCEDURE
--*******************************************************************
/*
Author: Ahliana Byrd, 20151201
Purpose: To take any table or view, export the data as a JSON file
EXAMPLE: EXEC SQLTableOrViewToJSON 'MyTable', 'C:\WhereIStowMyJSON\'
WARNING: This code will enable xp_cmdshell
WARNING: This code will create 2 tables and leave them so they can be checked later, easier for debugging
WARNING: This code will create a saved stored procedure, SQLTableOrViewToJSON
This creates a string to declare variables, declare a cursor, walk the cursor, and output the resulting strings to a table
The string is then executed, so that the entire procedure is essentially done in a virtual memory space
The string that will be executed is printed in the Messages window, so if something doesn't seem to be working,
you can scroll down, grab the generated script, and paste it into a new window so you can debug it
Metadata code by: marc_s on StackOverflow, http://stackoverflow.com/questions/2418527/sql-server-query-to-get-the-list-of-columns-in-a-table-along-with-data-types-no
*/
--*******************************************************************
--*******************************************************************
--This code will enable xp_cmdshell
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
-- To update the currently configured value for advanced options.
RECONFIGURE
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
-- To update the currently configured value for this feature.
RECONFIGURE
--*******************************************************************
--*******************************************************************
--Create the tables we need for SQL bits and output
PRINT'Beginning creating tables needed for SQL bits and output'
IFOBJECT_ID (N'dbo.SQLStatementsForJSONOutput', N'U') ISNULL
BEGIN
PRINT'<><><><><><><><><><> SQLStatementsForJSONOutput does not exist. It will be created. <><><><><><><><><><>'
CREATETABLE [dbo].[SQLStatementsForJSONOutput](
[ID] [int] IDENTITY(1,1) NOTNULL,
--[StatementOrder] [int] NULL,
[Descriptor] [nvarchar](50) NULL,
[StatementString] [nvarchar](max) NULL,
PRIMARYKEYCLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX=OFF, STATISTICS_NORECOMPUTE=OFF, IGNORE_DUP_KEY=OFF, ALLOW_ROW_LOCKS=ON, ALLOW_PAGE_LOCKS=ON) ON [PRIMARY]
) ON [PRIMARY]
END
IFOBJECT_ID (N'dbo.StringsForOutput', N'U') ISNULL
BEGIN
PRINT'<><><><><><><><><><> StringsForOutput does not exist. It will be created. <><><><><><><><><><>'
CREATETABLE [dbo].[StringsForOutput](
ID INTIDENTITY(1,1) PRIMARYKEY,
[String] [nvarchar](max) NULL
) ON [PRIMARY]
END
PRINT'Finished creating tables needed for SQL bits and output'
--*******************************************************************
--*******************************************************************
PRINT'Beginning main transaction'
BEGINTRANSACTION
--*******************************************************************
--Declare variables
DECLARE @Error INT=0
DECLARE @CompletionMessage VARCHAR (256)='Completed creating table data to export.'
DECLARE @Flowerbox VARCHAR (256)='********************************************************'
DECLARE @CRLF VARCHAR(20) =char(13) +char(10)
DECLARE @ColName VARCHAR(50)
DECLARE @ColType VARCHAR(20)
DECLARE @ColMaxLen INT
DECLARE @ColID INT
DECLARE @Metadata TABLE (ColName VARCHAR(50), ColType VARCHAR(20), ColID INT, ColMaxLen INT, ColPrecision INT, ColScale INT, ColIsNullable BIT, ColPrimaryKey BIT)
DECLARE @SQLString_Metadata VARCHAR(MAX)
DECLARE @SQLString_DeclareStatments VARCHAR(MAX)
DECLARE @SQLString_Table_Cursor VARCHAR(MAX)
DECLARE @SQLString_Table_Fetch VARCHAR(MAX)
DECLARE @SQLString_ToExecute VARCHAR(MAX)
DECLARE @SQLString_Builder VARCHAR(MAX)
DECLARE @SQLString_Composite VARCHAR(MAX)
DECLARE @Cursor_Name VARCHAR(20)
DECLARE @StatementString VARCHAR(MAX)
DECLARE @IfIsNotNull VARCHAR(MAX)
DECLARE @StringBuilderClause VARCHAR(MAX) ='SET @StringToOutput += '
DECLARE @Begin VARCHAR(20) ='BEGIN'+ @CRLF
DECLARE @End VARCHAR(20) ='END'+ @CRLF
DECLARE @PostTest TABLE (ID INT, String VARCHAR(MAX))
PRINT'Finished declaring variables'
--*******************************************************************
--*******************************************************************
--Set variables
PRINT'Set variables'
SET @Cursor_Name ='Cur_TableData'
IFUPPER(LEFT(@TableName, 4)) ='DBO.'
BEGIN
SET @TableName =RIGHT(@TableName, LEN(@TableName) -4)
END
IFUPPER(LEFT(@ExportPath, 1)) !='\'
BEGIN
SET @ExportPath = @ExportPath +'\'
END
PRINT'Finished setting variables'
--*******************************************************************
--*******************************************************************
--Pre testing
PRINT'Pre testing'
--Check for the table to export
IFCOALESCE((OBJECT_ID (N'dbo.'+ @TableName, N'U')), (OBJECT_ID (N'dbo.'+ @TableName, N'V'))) ISNULL
BEGIN
PRINT'<><><><><><><><><><> '+ @TableName +' does not exist. Nothing to export. <><><><><><><><><><>'
GOTO EmergencyExitHatch
END
--*******************************************************************
--*******************************************************************
--If tables exist, truncate them
--Check for SQLStatementsForJSONOutput, create if not there, truncate
IFOBJECT_ID (N'dbo.SQLStatementsForJSONOutput', N'U') ISNULL
BEGIN
PRINT'<><><><><><><><><><> SQLStatementsForJSONOutput does not exist. It should have been created already. Exiting. <><><><><><><><><><>'
GOTO EmergencyExitHatch
END
ELSE
BEGIN
PRINT'Truncating SQLStatementsForJSONOutput'
TRUNCATETABLE SQLStatementsForJSONOutput
END
--Check for StringsForOutput, truncate
IFOBJECT_ID (N'dbo.StringsForOutput', N'U') ISNULL
BEGIN
PRINT'<><><><><><><><><><> StringsForOutput does not exist. It should have been created already. Exiting. <><><><><><><><><><>'
GOTO EmergencyExitHatch
END
ELSE
BEGIN
PRINT'Truncating StringsForOutput'
TRUNCATETABLE StringsForOutput
END
--*******************************************************************
--*******************************************************************
--Do yer stuff
--Metadata
--http://stackoverflow.com/questions/2418527/sql-server-query-to-get-the-list-of-columns-in-a-table-along-with-data-types-no
INSERTINTO @Metadata
SELECT
c.name'Column Name',
t.Name'Data type',
c.column_id,
c.max_length'Max Length',
c.precision ,
c.scale ,
c.is_nullable,
ISNULL(i.is_primary_key, 0) 'Primary Key'
FROM
sys.columns c
INNER JOIN
sys.types t ONc.user_type_id=t.user_type_id
LEFT OUTER JOIN
sys.index_columns ic ONic.object_id=c.object_idANDic.column_id=c.column_id
LEFT OUTER JOIN
sys.indexes i ONic.object_id=i.object_idANDic.index_id=i.index_id
WHERE
c.object_id=OBJECT_ID(@TableName)
SET @Error +=@@ERROR
PRINT'Error count = '+CONVERT(VARCHAR(20), @Error)
SELECT*FROM @Metadata
SET @SQLString_Table_Cursor ='DECLARE '+ @Cursor_Name +' CURSOR FORWARD_ONLY FOR SELECT '
SET @SQLString_Table_Fetch ='FETCH NEXT FROM '+ @Cursor_Name +' INTO '
SET @SQLString_DeclareStatments ='DECLARE '
SET @SQLString_Builder =''
SET @SQLString_Composite =''
DECLARE Cur_Metadata CURSOR FOR SELECT ColName, ColType, ColMaxLen, ColID FROM @Metadata
OPEN Cur_Metadata
FETCHNEXTFROM Cur_Metadata INTO @ColName, @ColType, @ColMaxLen, @ColID
WHILE@@FETCH_STATUS=0
BEGIN
SET @SQLString_DeclareStatments +='@'+ @ColName +' '+ @ColType
SET @IfIsNotNull ='IF '+'@'+ @ColName +' IS NOT NULL'+ @CRLF
IFCHARINDEX('CHAR',@ColType) >0
BEGIN
IF @ColMaxLen >0
BEGIN
SET @SQLString_DeclareStatments +='('+CONVERT(NVARCHAR(20), @ColMaxLen) +')'
END
ELSE
BEGIN
SET @SQLString_DeclareStatments +='(MAX)'
END
SET @SQLString_Builder ='''"'+ @ColName +'": "'' + RTRIM(CONVERT(NVARCHAR(MAX), @'+ @ColName +')) + ''",'''+ @CRLF
SET @SQLString_Composite += @IfIsNotNull + @Begin + @StringBuilderClause+ @SQLString_Builder + @End + @CRLF
END
IFCHARINDEX('DATE',@ColType) >0
BEGIN
SET @SQLString_Builder ='''"'+ @ColName +'": "'' + RTRIM(CONVERT(NVARCHAR(MAX), @'+ @ColName +')) + ''",'''+ @CRLF
SET @SQLString_Composite += @IfIsNotNull + @Begin + @StringBuilderClause+ @SQLString_Builder + @End + @CRLF
END
IFCHARINDEX('INT',@ColType) >0
BEGIN
SET @SQLString_Builder ='''"'+ @ColName +'": '' + RTRIM(CONVERT(NVARCHAR(MAX), @'+ @ColName +')) + '','''+ @CRLF
SET @SQLString_Composite += @IfIsNotNull + @Begin + @StringBuilderClause+ @SQLString_Builder + @End + @CRLF
END
IFCHARINDEX('NUMERIC',@ColType) >0
BEGIN
SET @SQLString_Builder ='''"'+ @ColName +'": '' + RTRIM(CONVERT(NVARCHAR(MAX), @'+ @ColName +')) + '','''+ @CRLF
SET @SQLString_Composite += @IfIsNotNull + @Begin + @StringBuilderClause+ @SQLString_Builder + @End + @CRLF
END
IFCHARINDEX('BIT',@ColType) >0
BEGIN
SET @SQLString_Builder ='''"'+ @ColName +'": '' + '
SET @SQLString_Builder +='CASE WHEN @'+ @ColName +' = 1 THEN ''true'' ELSE ''false'' END + '','''+ @CRLF
SET @SQLString_Composite += @IfIsNotNull + @Begin + @StringBuilderClause+ @SQLString_Builder + @End + @CRLF
END
SET @SQLString_DeclareStatments +=', '
SET @SQLString_Table_Cursor += @ColName +', '
SET @SQLString_Table_Fetch +='@'+ @ColName +', '
FETCHNEXTFROM Cur_Metadata INTO @ColName, @ColType, @ColMaxLen, @ColID
END
CLOSE Cur_Metadata
DEALLOCATE Cur_Metadata
--Remove trailing space
SET @SQLString_DeclareStatments =SUBSTRING(@SQLString_DeclareStatments,1, DATALENGTH(@SQLString_DeclareStatments)-2)
--Remove the trailing comma and space
SET @SQLString_Table_Cursor =SUBSTRING(@SQLString_Table_Cursor,1, DATALENGTH(@SQLString_Table_Cursor)-2)
SET @SQLString_Table_Fetch =SUBSTRING(@SQLString_Table_Fetch,1, DATALENGTH(@SQLString_Table_Fetch)-2)
--Add the tablename
SET @SQLString_Table_Cursor +=' FROM '+ @TableName
--Build the executable pieces in a table, easier to debug that way
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Declare String To Output', 'DECLARE @StringToOutput NVARCHAR(MAX)')
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Declare BitValue', 'DECLARE @BitValue BIT')
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Truncate Output Table', 'TRUNCATE TABLE StringsForOutput')
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Declare Statements', @SQLString_DeclareStatments + @CRLF)
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Insert Opening Bracket', 'INSERT INTO StringsForOutput VALUES (''['')'+ @CRLF)
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Table Cursor', @SQLString_Table_Cursor)
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Open Cursor', 'OPEN '+ @Cursor_Name)
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Table Fetch', @SQLString_Table_Fetch + @CRLF)
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('While Fetch', 'WHILE @@FETCH_STATUS = 0')
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('BEGIN', 'BEGIN')
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Open Object', 'SET @StringToOutput = ''{'''+ @CRLF)
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Build Object', @SQLString_Composite)
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Remove Trailing Comma', 'SET @StringToOutput = SUBSTRING(@StringToOutput,1, LEN(@StringToOutput)-1)')
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Close Object', 'SET @StringToOutput += ''},''')
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Table Fetch', @SQLString_Table_Fetch)
--If this is the last record, strip off the trailing comma for the export
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Strip very last comma for export, Part 1', 'IF @@FETCH_STATUS != 0'+ @CRLF)
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Strip very last comma for export, Part 2', @Begin)
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Strip very last comma for export, Part 3', 'SET @StringToOutput = SUBSTRING(@StringToOutput,1, LEN(@StringToOutput)-1)'+ @CRLF)
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Strip very last comma for export, Part 4', @End)
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Insert Object', 'INSERT INTO StringsForOutput VALUES (@StringToOutput)')
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('END', 'END')
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('CLOSE', 'CLOSE '+ @Cursor_Name +' ')
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('DEALLOCATE', 'DEALLOCATE '+ @Cursor_Name +' ')
INSERTINTO SQLStatementsForJSONOutput (Descriptor, StatementString)
VALUES ('Insert Closing Bracket', 'INSERT INTO StringsForOutput VALUES ('']'')')
PRINT'Finished inserting statements into SQLStatementsForJSONOutput'
--Get the statement pieces out of the table, assemble, execute
PRINT'Get the statement pieces out of the table, assemble, execute'
SET @SQLString_ToExecute =''
DECLARE Cur_SQLStrings CURSORFORWARD_ONLYSTATIC FOR SELECT StatementString FROM SQLStatementsForJSONOutput ORDER BY ID
OPEN Cur_SQLStrings
FETCHNEXTFROM Cur_SQLStrings INTO @StatementString
PRINT'Building string'
WHILE@@FETCH_STATUS=0
BEGIN
SET @SQLString_ToExecute += @StatementString + @CRLF
FETCHNEXTFROM Cur_SQLStrings INTO @StatementString
END
CLOSE Cur_SQLStrings
DEALLOCATE Cur_SQLStrings
PRINT'Finished building string'
PRINT''
PRINT''
PRINT @Flowerbox
PRINT @SQLString_ToExecute
PRINT @Flowerbox
PRINT''
PRINT''
PRINT'Executing string'
EXEC(@SQLString_ToExecute)
--*******************************************************************
--*******************************************************************
--Post testing
PRINT'POST Testing'
INSERTINTO @PostTest
SELECT ID, String
FROM StringsForOutput
IFNOTEXISTS(
SELECT*FROM @PostTest
)
BEGIN
SELECT*FROM @PostTest
SET @Error +=1
PRINT'Post testing shows errors. PLEASE CHECK.'
END
PRINT'Finished POST testing.'
--*******************************************************************
--*******************************************************************
--This is the label for just bailing out of the procedure, used above if we know we're done and need to just leave
EmergencyExitHatch:
--*******************************************************************
--*******************************************************************
--Housecleaning
--*******************************************************************
IF @Error >0
BEGIN
ROLLBACK
PRINT'/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\'
PRINT'\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/'
PRINT'Error count = '+CONVERT(VARCHAR(20), @Error)
PRINT'ROLLING BACK TRANSACTION'
END
ELSE
BEGIN
COMMITTRANSACTION
PRINT @Flowerbox
PRINT @Flowerbox
PRINT'Completed - '+ @CompletionMessage
END
--*******************************************************************
--The export has to be outside of the main transaction
DECLARE @DateTime VARCHAR(MAX) = (SELECTCONVERT(VARCHAR(20),GETDATE(),112) +'_'+LEFT(REPLACE(CONVERT(VARCHAR,GETDATE(),114),':',''),6))
DECLARE @ExportFileName VARCHAR(MAX)
DECLARE @DatabaseName VARCHAR(MAX) = (SELECTDB_NAME() AS DataBaseName)
IF @ExportName =''
BEGIN
SET @ExportFileName = @ExportPath + @TableName +'_'+ @DateTime +'.json'
END
ELSE
BEGIN
SET @ExportFileName = @ExportPath + @ExportName
END
--*******************************************************************
--Check for the table to export
IFCOALESCE((OBJECT_ID (N'dbo.'+ @TableName, N'U')), (OBJECT_ID (N'dbo.'+ @TableName, N'V'))) ISNULL
BEGIN
PRINT'<><><><><><><><><><> '+ @TableName +' does not exist. Nothing to export. <><><><><><><><><><>'
END
ELSE
BEGIN
--Use BCP to export the table
--If you don't ORDER BY ID, the closing bracket will end up in the middle, SQL oddity in the INSERT INTO statement
PRINT'Starting export.'
DECLARE @cmd varchar(1000)
SET @cmd ='bcp "SELECT String FROM '+ @DatabaseName +'..StringsForOutput ORDER BY ID" queryout '+ @ExportFileName +' -c -t, -UTF8 -T -S '+@@servername
PRINT @cmd
EXECmaster..xp_cmdshell @cmd
PRINT'Finished export.'
END
--*******************************************************************
END--END OF STORED PROCEDURE