How to generate sql scripts from a query - sql

Does anyone know how to generate SQL scripts from a query?
For example,
Script some tables.
Do custom action 1.
Script the views.
Do custom action 2.
Etc.

It sounds like you want to write a cursor to execute custom SQL. This is common and easy to do. What you need to do is specify a few things to help us more completely answer your question:
What type of SQL server are you using? (MSSQL, Oracle, MySQL)
What language are you writing in? (Java, C++, PL/SQL, TSQL)
You can either write code (Java / C++) to generate SQL from a query, or possibly use a cursor to iterate over recordsets (PL/SQL / TSQL). You can use the results to give you information that can then be executed as SQL via an exec (of some kind depending on the language).

... but please investigate SQL injection before implementing dynamic SQL. Look into Parameterized Queries...

With Microsoft Sql Server, the best way to script database objects is to use SMO. Sql Management Objects is a c# api, but you could always execute t-sql scripts from c# using a SqlClient.

You could want something like
select 'UPDATE '+table_name+ ' SET description=''(new!) ''+description WHERE description_date>''2008-11-01'''
from information_schema.tables where table_name like '%Description'
(this query generates queries which prepend value of description column with '(new!) ' for each recent row in each table which name ends with 'Description' in a fictional database).
The system view INFORMATION_SCHEMA.TABLES contains data about all database tables, there are also INFORMATION_SCHEMA.VIEWS, INFORMATIONS_CHEMA.COLUMNS and other system views in INFORMATION_SCHEMA table schema.
Hope this will help.

Related

Migrate data from SQL Server to PostgreSQL

I have a stored procedure function as well as table in the SQL Server enterprise 2014. I also have data in the table. Now I need same table and data in PostgreSql(pgAdmin4).
Can anyone suggest to me the idea to migrate data to POSTGRESQL or any idea on creating the SQL script so that I can use psql to run the script?
Depending on how much data you have, you could script out the table and data. Then you could tweak the script as needed for PostgreSQL:
Right click on the SQL database > Tasks > Generate Scripts
On the "Choose Objects" screen, select your specific table then select "Next>"
On the "Set Scripting Options" screen, select "Advanced"
Find the option called "Types of data to script", then select "Schema and data" and select "OK"
Set the filename and continue through the dialog until the file is generated
Tweak the sql script for any specific PostgreSQL syntax
If there is a larger amount of data, you might look into some type of data transfer tool like SSIS.
Exporting the table structure and data as Josh Jay describes will likely require some fixes where the syntax doesn't match, but it should be doable if not tedious. Luckily there are existing conversion tools available to help.
You could also try using a foreign data wrapper to map the tables in SQL Server to a running instance of PostgreSQL. Then it's just a matter of copying tables. Depends on your needs and where each database server is located relative to one another.
The stored procedures will be far more difficult to handle unfortunately. While Oracle's pl/sql language is substantially similar to PostgreSQL's pl/pgsql, MS SQL Server/Sybase's TransactSQL dialect on the other hand is different enough to require rewrites. If the TransactSQL functions also access .Net objects, the migration task may end up far more difficult as you reimplement dependencies or find logical equivalents.

What is a dynamic SQL query, and when would I want to use one?

What is a dynamic SQL query, and when would I want to use one? I'm using SQL Server 2005.
Here's a few articles:
Introduction to Dynamic SQL
Dynamic SQL Beginner's Guide
From Introduction to Dynamic SQL:
Dynamic SQL is a term used to mean SQL code that is generated programatically (in part or fully) by your program before it is executed. As a result it is a very flexible and powerful tool. You can use dynamic SQL to accomplish tasks such as adding where clauses to a search based on what fields are filled out on a form or to create tables with varying names.
Dynamic SQL is SQL generated by the calling program. This can be through an ORM tool, or ad-hoc by concatenating strings. Non-dynamic SQL would be something like a stored procedure, where the SQL to be executed is predefined. Not all DBA's will let you run dynamic SQL against their database due to security concerns.
A dynamic SQL query is one that is built as the program is running as opposed to a query that is already (hard-) coded at compile time.
The program in question might be running either on the client or application server (debatable if you'd still call it 'dynamic') or within the database server.

How can I import a database schema into MS Access 2003 from sql text file?

I have a database schema generated in a text file (DDL - MS Access compliant).
Where is the option in MS Access to import that schema into an empty database ?
I'm not aware of any import for DDL.
However, DDL contains the definition for the schema.
You simply have the execute DDL as you would any query.
Either create a query, put it in sql mode, paste your ddl, and execute
or....
Create a VBA Sub to essentially do the same: currentdb.execute SQL
Good Luck
To execute a SQL DDL in the SQL View of a Query object, you may need to change the Access user interface to ANSI-92 Query Mode. While the 'traditional' query mode (ANSI-89 Query Mode) supports a SQL DDL syntax it is very limited.
The Access database engine can only execute one SQL statement (DML, DDL or DCL) at a time. To execute a SQL script consisting of multiple SQL statement, you need something to parse individual SQL statements, so it really helps if your script has semicolon ; characters separating them, then execute each statement on at a time i.e. synchronously. If you are doing this in VBA code you are better off using ADO because it always uses ANSI-92 Query Mode.
See if this helps: http://support.microsoft.com/kb/180841
I have been very succesful with reverse / forward engineering MS Access databases with Dezign for Databases by Datanamic. It reads all kinds of DDL scripts (from almost all available database) and can translate between different databases. There is a free trial available.

CREATE TABLE reverse engineering in Oracle

In Oracle SQL Developer, there's a "SQL" tab for each table. This tab contains most of the SQL code (CREATE TABLE, CREATE TRIGGER, etc) that's needed to recreate the table.
Is this information available programatically from the database system, or is this an application feature of SQL Developer? If the former, what commands/statements would I need to run to retrieve this information? If the later, are there any clever ways to get SQL Developer to export these statements?
If you are using Oracle 9i+ then you are looking for the DBMS_METADATA package. http://download.oracle.com/docs/cd/B10500_01/appdev.920/a96612/d_metada.htm. It will allow you to extract whatever DDL you want.
If you are looking for more specific information there is a whole host of views you can access for specific data elements similar to the ones given by #Quassnoi.
There are lots of information, but here are the main queries:
SELECT *
FROM dba_tables
SELECT *
FROM dba_tab_columns
SELECT *
FROM dba_ind_columns
To see what SQL Developer actually outputs, enable trace for all sessions with a LOGON TRIGGER and look into the trace file created by SQL Developer's internal session.
You are looking for the DDL of your database objects.
You can use the Oracle bundled DBMS_METADATA package to get it, from any PL/SQL prompt, with the GET_DDL function.
I use TOAD vs Oracle SQL Developer.
When I click on a "Script" tab when viewing an object (like a table) TOAD executes a whole host of queries and then compiles the "script" from the output of all of these queries.
dba_tables
dba_tab_columns
dba_ind_columns
...
I think replicating this functionality would be a tedious task.

Dynamic SQL for updating any table !

How to create a dynamic SQL statement, that will update any table given as one of parameter. Here I believe, i couldn't use "Set Column1 = Value ....." as the columns will differ according to the table.
This is an extremely poor idea. You can create massive havoc with your database doing such a thing. I can't imagine any dba who would allow it. You need to know the specifics of a table to insert into it properly, you need to be aware of what fields are required and what fields have default values. You need to know what kind of information and data types should be in each field so that you do not send bad data to the database. One proc that does all cannot properly check these things and certainly can't ever be properly tested. Further it means permissions must be at the table level which is a poor choice for internal security as well as for SQL injection attacks.
Could you provide more context? Are you executing arbitrary SQL statements from within scripts, such as Perl, PHP, or Python? Are you just trying to get a command-line .sql script working? What database server are you working on?
The solution can vary widely depending on your situation.