Transact SQL :: Creating Table In Particular Database When Run Dynamic Script

May 13, 2015

I have a question regarding the dynamic sql. I have a script which which deletes all the foreign keys and re- creates it. So, I have created a table instead of a temp table. Now I need to create that foreign keys table in such a way that in which ever database I run the script, this  foreign keys table should be created in that particular database.

For example:

IF OBJECT_ID('tempdb..keys','U') IS NOT NULL
DROP TABLE keys
CREATE TABLE keys.[@sourceserver],[@database]. (RowId INT PRIMARY KEY IDENTITY(1, 1),
ForeignKeyConstraintName NVARCHAR(200),
ForeignKeyConstraintTableSchema NVARCHAR(200),
ForeignKeyConstraintTableName NVARCHAR(200),
ForeignKeyConstraintColumnName NVARCHAR(200)

View 2 Replies


ADVERTISEMENT

Transact SQL :: Query To Check Properties On A Table When Creating Database?

May 20, 2015

I'm wondering if there is some sql I can run to check properties on a table. This would be used to verify things like data types, allow nulls and default values have been set to avoid mistakes. This could be done manually one table and one column at a time, but it would be a lot easier to look at it in the results window.

View 5 Replies View Related

Creating Dynamic Table

Oct 29, 2007

Hello all,

I have the following situation.
Our customer would like to generate a raw data export report from specific customer databases.

I have an administrative database with a customer table. In this customer table each customer has it's on specific
customerId guid.
Each customer also has it's own customer database that is named: Customer_ + guid of the customer in the admin
database (eg: Customer_982240e79f424fb0a1d4bed16267245d).
This customer database has 1 main table (dbo.Data), but the design can be different depending on the customer.
Our customer would like to have the possibility to select specific fields from the table to export to an excel file.
So i never know in advance how much fields there will be in the table.

What i want to achieve is to generate a report where i can select a specific customer from a list (from the admin database). Then be able to view all the available fields inside the table (like a dataset or something) and then let the
customer select which fields he wants in his data export report.

Can this be achieved in RS2005?

Greetz
Vinnie

View 3 Replies View Related

Creating Table Using Dynamic SQL

Jul 26, 2007

I have the following dataset using dynamic SQL which works when i execute it, when i try to create a table using this dataset i cant see any fields. Does anyone know why dynamic SQL doesnt work ?

Declare @TopRange int
Declare @BottomRange int
Declare @SQL Varchar(1000)
IF @Param_leadage = '91+'
SET @TopRange = 91
ELSE
Set @TopRange = RTRIM(LEFT(REPLACE(@Param_leadage,'-',''),2))

IF @Param_leadage = '91+'
SET @BottomRange = 4000
ELSE
Set @BottomRange = LTRIM(RIGHT(REPLACE(@Param_leadage,'-',''),2))

SET @SQL = 'SELECT dbo.tblCustomer.idStatus, dbo.tblCustomer.idCustomer, dbo.tblCustomer.DateSigned' +
' FROM dbo.tblCustomer' +
' WHERE DateDiff(day, dbo.tblCustomer.DateSigned, GetDate()) >= ' + convert(varchar,@TopRange) + ' AND DateDiff(day,dbo.tblCustomer.DateSigned, GetDate()) <= ' + convert(varchar,@BottomRange)
IF @Param_status = 'Online Churn'
SET @SQL = @SQL + ' AND dbo.tblCustomer.idStatus = 4 or dbo.tblCustomer.idStatus = 5 or dbo.tblCustomer.idStatus = 11'
ELSE
SET @SQL = @SQL + ' AND dbo.tblCustomer.idStatus = ' + @Param_idstatus

EXEC(@SQL)

View 6 Replies View Related

SQL Server 2012 :: Creating Dynamic Pivot Table

Jul 2, 2014

I am having trouble figuring out why the following code throws an error:

declare
@cols nvarchar(50),
@stmt nvarchar(max)
select @cols = ('[' + W.FKStoreID + ']') from (select distinct FKStoreID from VW_PC_T) as W
select @stmt = '
select *

[Code] ...

The issue that I am having is:

Msg 245, Level 16, State 1, Line 4
Conversion failed when converting the varchar value '[' to data type int.

I know that I have to use the [ ] in order to run the dynamic sql. I am not sure what is failing and why as the syntax seems to be clean to me (obviously it is not).

View 6 Replies View Related

Creating A Dynamic Global Temp Table Within A Stored Procedure

Sep 7, 2006

hi,I wish to create a temporary table who's name is dynamic based on theargument.ALTER PROCEDURE [dbo].[generateTicketTable]@PID1 VARCHAR(50),@PID2 VARCHAR(50),@TICKET VARCHAR(20)ASBEGINSET NOCOUNT ON;DECLARE @DATA XMLSET @DATA = (SELECT dbo.getHistoryLocationXMLF (@PID1, @PID2) as data)CREATE TABLE ##@TICKET (DATA XML)INSERT INTO ##@TICKET VALUES(@DATA)ENDis what i have so far - although it just creates a table with a name of##@TICKET - which isn't what i want. I want it to evaluate the name.any ideas?

View 16 Replies View Related

Transact SQL :: Return Recordset From Dynamic Table

Sep 25, 2015

I tried to create a dynamic table, fill in it and return it as recordset. The codes as this:

Declare @tbl Table(id int, name varchar(100), age int) 
Insert Into @tbl(id, name, age)
Values(1, 'James, Lee', 28),
   (2, 'Mike, Richard', 32),
   (3, 'Leon Wong', 29)
Select * From @tbl Order By age

It works well in "SQL Query Ananizer". But return no records in ASP page.

View 5 Replies View Related

Transact SQL :: Dynamic Partition For Partitioning Table

Jul 31, 2015

I am new to Partitioning tables. My scenario is as listed below.

I am getting Monthly Transaction data on Every First Monday of the Month and I want to do partition for those data.

For Example: Let's say I will get my next monthly data on August 3rd 2015 which is First Monday of the month of August.

I want those Transaction data to go in new partitioned FileGroup in my existing partitioned table. How can I do partition for this kind of scenario ? Can we create one or multiple Stored Procedure which will create New Partition and load data in that partition ? 

FYI, this monthly data will be loaded in Staging table and that table has LoadDate column which will have 2015-08-03 in it.  I am using SQL 2012 Enterprise edition.

View 17 Replies View Related

SQL Server 2012 :: Creating A View Or Procedure From Dynamic Pivot Table

May 29, 2015

I have written a script to pivot a table into multiple columns.

The script works when run on its own but gives an error when i try to create a view or aprocedure from the same script. The temporary table #.... does not work so i have converted it to a cte.

Here is a copy of the script below

-- Dynamic PIVOT
IF OBJECT_ID('#External_Referrals') IS NULL
DROP TABLE #External_Referrals;
GO
DECLARE @T AS TABLE(y INT NOT NULL PRIMARY KEY);

[Code] ....

View 7 Replies View Related

Transact SQL :: Use Dynamic Table Names And Get Return Value From The Query

Sep 16, 2015

I don't know why this is so difficult. What I want to do is take a table name as a parameter to build a query and get an integer value from the result of the query. But from all of the research I have been doing, Dynamic SQL is bad in SQL server because of SQL Injections. But my users are not going to be supplying the table names.

Things I have learned:

 - SQL Functions cannot use Exec to execute query strings.
 - SQL Functions can return a concatenated string that could be used by a stored procedure to Exec the query string.

So how can I write a stored procedure that will
 
1. take a parameter
2. Pass the parameter to a function that will return a string
3. Execute that string as SQL
4. Get a return value from that SQL statement
5. Then finally, from a View, how can I pass a parameter to the stored procedure and get the returned value from the stored procedure to be used as a field in the View?

Numbers 3, 4, and 5 are where I am really stuck. I guess I don't know the proper syntax and limitations of SQL Server.

View 14 Replies View Related

Transact SQL :: Unpivot With Dynamic Columns Or Redesign Relational Table?

Sep 3, 2015

I want to use column name to be join another tables.

I have invoice table to store detail of invoice and post some column ' s record to another table .

Invoice table
Invoice_Name  |   Invoice_Amount |  Invoice_Vat | Invoice_Total
Inv001            |          1000           |       70          |     1070             

Account_table
Account_No |  Account_Number | Data_Source
JV001          |     1111               |    Invoice_Amount  ---->1000
JV001          |     1112               |    Invoice_Vat         ---->    70
JV001          |     1113               |    Invoice_Total       ----> 1070 

I want to join  Invoice table to Account_table

ON  Invoice_Amount , Invoice_Vat , Invoice_Total with Data_Source

The way i got so far I unpivot  Invoice table  column into row and join with Account_table .

The problem is ,  if the column in Invoice_table are created , I must used dynamic columns to do this in sql query.

View 7 Replies View Related

Transact SQL :: How To Insert Dynamic Column Values Of A Table To Variables

Jul 18, 2015

I am trying to insert different number of columns into variables.  This is what it does If I use a static columns.

declare @AccountType nvarchar(10)
declare @Total numerical(15,2)
declare @1 numerical (15,2)
declare @2 numerical (15,2)
declare @3 numerical (15,2)

#MonthtoDate  temp table is created using a dynamic pivot query. 

Data looks like this :

Account Type  1 2
3 Total
Type 1 3
0 4 7
Type 2 5
7 1 13

Select @AccountType = AcctType , @Total = MonthToDate, @1 = [1], @2 = [2], @3 = [3]  from #MonthtoDate 

However the issue is with [1],[2],[3] columns. Those are the number of days of the month. If today is the 3rd day of the month, we only need to show 3 days. So the final table has column [1],[2],[3] and @AccountType and @Total .

We want to run this query everyday to get the moth to date values.If we run this tomorrow, it will have 4 date columns [1], [2],[3],[4] and @AccountType and @Total .

View 6 Replies View Related

Transact SQL :: How To Build Dynamic WHERE Clause In Openquery To Linked Database

Jul 17, 2015

I'd like to modify the dates within this where clause to be dynamic, building the date depending on the current year, but everything I try doesn't seem to be syntactically correct.

SELECT *
FROM Openquery(LS_CIS, 'select * from BI_WRKFLW_TASKS where (BI_EVENT_DT_TM>=''1/1/2011'' and (BI_NEEDED_DT_TM>=''1/1/2011''))OR (BI_EVENT_DT_TM>=''1/1/2011'' and BI_NEEDED_DT_TM is null)') AS derivedtbl_1
I'd like to replace ''1/1/2011''  in the where clause with something like:
CAST(CAST(YEAR (GETDATE())-4 AS varchar) + '-' + CAST(01 AS varchar) + '-' + CAST(01 AS varchar) AS DATETIME)

View 9 Replies View Related

Transact SQL :: How To Find All Dynamic Scripted Stored Procedure In Database

Jul 2, 2015

Is there any way/Process that we can find out all stored procedures from database where dynamic script has used in script.

View 6 Replies View Related

Transact SQL :: Database Role For Creating Stored Procedure?

Oct 2, 2015

I want to create database role which can be used for creating stored procedures like db_SPCreate.

User should be able to create SP on Schema PVR; and should not be allowed to create sP in otherthan schema and he can use any schema tables to create procedure.

[URL]

View 4 Replies View Related

Transact SQL :: Create Database Trigger Automatically Whenever New DB Is Creating?

Aug 5, 2015

I need to deploy the trigger in database whenever new DB is creating on the server.

View 6 Replies View Related

Transact SQL :: Dynamically Creating And Running A Database Restore Command

Jun 17, 2015

If I run the following command in a Query window it works:

RESTORE DATABASE CIS_Source_Data_Test FROM DISK = 'y:CIS_Source_Data_backup_2015_06_17_085557_7782407.bak' WITH RECOVERY, REPLACE

If I dynamically put together the command and store it in variable @cmd and then execute it using
exec sp_executesql @cmd or exec (@cmd) it does not work. I get the following:

Msg 2745, Level 16, State 2, Procedure CIS_Source_Data_Refresh, Line 92
Process ID 62 has raised user error 50000, severity 20. SQL Server is terminating this process.
Msg 50000, Level 20, State 1, Procedure CIS_Source_Data_Refresh, Line 92
RESTORE DATABASE is terminating abnormally.
Msg 0, Level 20, State 0, Line 0

A severe error occurred on the current command.  The results, if any, should be discarded.

Why it won't work when I try to create and run it dynamically?

View 8 Replies View Related

SQL 2012 :: Creating Dynamic SSIS File Format - Dynamic CSV File As Output

Mar 2, 2014

I am trying to create an ssis package with dynamic csv file as output. and out format contains query output.

sample file name:

Unique identifier + query output + systemdate();

The expression is looking like this.

@[User::FilePath] + @[User::FileName] + ".CSV"

-- user filepath is a variable from ssis package. File name is the output from SQL query. using script task i have assigned the values to @[User::FileName] .

When I debugged the script task the value getting properly but same variable am using for Flafile destination. but its not working.

View 3 Replies View Related

Transact SQL :: Verify Inserted Values From One Table (in CSV File) With Another Table (in Database)

Aug 4, 2015

I am looking for a Sql query to verify the inserted values from one table(in CSV file) with another table(in sql database)

For example: I have below Values column that is present in once CSV file, after my data migration the values get stored in Results table under Message column.

I need to very whether values(1X,1Y) are inserted in Message record "successfully inserted value 1X"

Values (CSV)
1X
1Y

Results Table(SQL)
CreatedDate                   Message
2015-08-04 08:45:29.203  successfully inserted value 1X
2015-08-04 08:44:29.103  TEst pass
2015-08-04 08:43:29.103  successfully inserted value 1X
2015-08-04 08:42:29.203  test point
2015-08-04 08:35:29.203  successfully inserted value 1Y
2015-08-04 08:30:29.203  Test Pass
2015-08-04 08:28:29.203  successfully inserted value 1Y

If all values are inserted:

Output:
All values from values table are inserted successfully
Total count of values inserted: 2
If only few values are inserted, example only 1X from Values table is inserted in Message

Example:
Results Table CreatedDate     Message
2015-08-04 08:45:29.203  successfully inserted value 1X
2015-08-04 08:44:29.103  TEst pass
2015-08-04 08:43:29.103  successfully inserted value 1X
2015-08-04 08:42:29.203  test point

Output:
All values from values are not inserted successfully in result table.
Total count of values inserted: 1
Missing Values not inserted in results table are: 1Y

View 3 Replies View Related

Creating A Table In Database?

Nov 28, 2014

I am having problems creating a table in my first database.

When I script:

CREATE TABLE ship (mmsi INT, time INT, longitude INT, latitude INT, cog INT, sog INT, heading INT, navsat INT, imo INT, name CHAR, callsign VARCHAR, type INT, a INT, b INT, c INT, d INT, draught INT, dest CHAR, eta INT); I am returned with an error 1064 with regads to the attributes from "Typ" onwards.

From what I can see this should work.

View 3 Replies View Related

Creating A Table Using Data From Another Database

Jan 25, 2007

hi, i'm trying to create a table and populate it with data from another database residing on the same server. i've done this on oracle using tables within the same database and am just making a first effort with the added twist of a different database. this is what i've been doing so far...

CREATE TABLE facility_dimension
(
fac_id INT IDENTITY(1,1),
tri_fac_id CHAR(17),
fac_nameVARCHAR(100),
street VARCHAR(100),
city VARCHAR(100),
county VARCHAR(50),
state VARCHAR(4),
longitude REAL,
latitude REAL,
PRIMARY KEY(fac_id)
)
SELECT tri_facility_id, facility_name, street_address,
city_name, county_name, state_abbr, fac_latitude,
fac_longitude
FROM TRI_2004.form_1;

....where TRI_2004 is the other database and form_1 is the table. the result is creation of the new table and then the output of the secondary query. i'm assuming this can even be done but if it can't that would be helpful to know as well. thanks in advance!

View 2 Replies View Related

Single Table Structured Dynamic Relational Database

Apr 10, 2008

Sharepoint is a pretty darn dynamic service and that got me thinking of how databases are created.
Just wondering out loud, surely someone has thought of creating databases in such a manner, but I don't know if it's a thought that has been struck down.

It would look something like this:
Single Table
ID uniqueidentifier PK
ParentID uniqueidentifier FK to ID
Name nvarchar(MAX)

Value nvarchar(MAX)

In this manner, you would create your database "columns" as needed in the data-layer.

If that is too strict, (every datatype would be encoded to base64), you could create a value option for basically every data type. EG. nvarchar(max), nvarbinary(max).... and add another field that describes the data-type to be used for that "column"
ID uniqueidentifier PK
ParentID uniqueidentifier FK to ID
Name nvarchar(MAX)
DataType nvarchar(50) //constrained to allowable datatypes
MaxLen nvarchar(31) //ahh, what the hey, let's add this for sniggles.
ValueNvarchar nvarchar(MAX) nullable

ValueNvarbin nvarbinary(MAX) nullable

....

Now, to allow the "values" for those "columns", you may be able to still use the single-table approach, but it may be better to have an extra table for that (probably even a different partition and drive).


Things to consider, indexing.....
In development, the data-layer would handle the creation/reading of table columns.
The business-layer, which could be many for different parts of a company, would make it's requests to the DL. It may need a username, and the DL would either just create it, or suggest an already existing username column. The path to that username may not be where a particular biz element wants it, so they will ask the DL create another under a diff path.

The business-layer is probably the most important reason for wanting a single dynamic table.

In the end, the relation structure could be like:
Human //dir, no value, no parent (root)
FirstName //value - text
LastName //value - text
Parent1 //value - Me Id
Sibling1 //value - Me Id
SiblingN //value - Me Id

School //dir, no val
ParentId //value - Id (perhaps category would be Building)
Name //value - text

The sibling N would be an example of how a table may need to be dynamic. A positive of the single-table approach is no limitation on number of "columns". Another is the ease to move a hierarchical structure if needed. School may want to be University instead of just "school" and be placed as a child of "school".

Looking for any thoughts on the subject,
Nathan

View 1 Replies View Related

Error Message While Creating Table In The Database

Jan 25, 2005

Hi

I created database using SQL server and runs under Cassini. The creation of database is ok but I have a problem when I am creating the table in database. Whenever I execute the code to create the tables, it shows the error message like 'Server not found' or just hang there. Does anybody know why it hang while I am creating the table? Is it because of the code or it's the time out error. Pls help as I am very new to this area.

MZ

View 1 Replies View Related

Creating Database And Table On MS MSQL Server

Jul 20, 2005

Hi All,I want to use MS sql server edition 2000. I have installed the server. Now iwant to create the database on this server with tables and triggers. Canplease someone suggest me how to do this ?Thanks a lot,Dinesh

View 1 Replies View Related

Problem In Creating Database And Table In One Shot

May 9, 2006

I need to create a database and then create tables in it..

 IF  EXISTS (SELECT name FROM sys.databases WHERE name = N'DB1')
 DROP DATABASE [DB1]

 -- create a new database
 CREATE DATABASE [DB1] ON  PRIMARY 
 ( NAME = N'DB1', FILENAME = N'D:DB1.mdf' ,
SIZE = 51200KB , MAXSIZE = UNLIMITED, FILEGROWTH = 30720KB )
  LOG ON
 ( NAME = N'DB1_log', FILENAME = N'D:DB1_log.ldf' , SIZE = 2048KB , MAXSIZE = UNLIMITED , FILEGROWTH = 30720KB )
  COLLATE Latin1_General_CI_AS


CREATE TABLE [DB1].[dbo].[SALES](
    [PERIOD] [int] NOT NULL,
    [LOC] [nchar](3) COLLATE Latin1_General_CI_AS NOT NULL
   ) ON [PRIMARY]


If i run the above statement one after one, they work; however, if I run all of them together (or in sp), the following error raised:

Msg 2702, Level 16, State 2, Line 43
Database 'DB1' does not exist.

May I know how can i create a database and then immediately the tables in sp!

Thanks

View 5 Replies View Related

Creating A Table And Adding Rows To Database In Studio Management

Aug 12, 2015

I am trying to use the following Query to create the table Agents and add rows to it.

USE REMAXCLASSIC;
IF OBJECT_ID ('dbo.Agents', 'U') IS NOT NULL
DROP TABLE Agents;
GO
CREATE TABLE Agents

[Code] ....

I get the following error messages:

Msg 102, Level 15, State 1, Line 34 Incorrect syntax near '0.25'
Msg 105, Level 15 mark after the character string ');

View 2 Replies View Related

Creating Dynamic Reports

Apr 22, 2007

Hello.

I wanted to know a way to create dynamic reports using reporting / analysis services in SQL Server 2005 / SSIS tool.



I want user to give inputs and generate reports based on those inputs.

Please guide me on this issue.

Thank you.



Regards,

Prathamesh

View 1 Replies View Related

Help Creating Dynamic Reports

Jan 9, 2007

I can create static report with Report Server, but wanted if anyone can help me create a report that is dynamic and regenerates with new data as it comes in.



Thanks so much!

View 1 Replies View Related

Transact SQL :: Report Table Sizes In Each Database On Server

Aug 4, 2015

The below query works perfectly fine, except that it  produces many outputs instead of one continuous table that can be easaly converted to xml / csv by copying it from the "Results" window. 

What I need is a query that will produce a single result for all the tables in all the databases on the server.

The results:

The query:

DECLARE @begin INT = 1, @end INT, @sql NVARCHAR(MAX)
DECLARE @CREATE_TEMPLATE VARCHAR(MAX);
DECLARE @DBNAME VARCHAR(255);
DECLARE @SQL_SCRIPT VARCHAR(MAX);
SELECT @end = COUNT(name) FROM sys.databases
SET @CREATE_TEMPLATE = '

[Code] ....

View 11 Replies View Related

Transact SQL :: Import Bulk CSV Files In Database Table

Nov 12, 2015

I have more than 500 CSV files with a similar structure [Same column name and same data format]. I would like to load these files in a database table on the SQL Server 2014 database.

View 21 Replies View Related

Transact SQL :: Query To Retrieve To What Database A Table Belongs

Jul 16, 2015

I need a query to list the tables in SQL sever with respective database they belong across databases.

I can obtain list of tables from Sys.Tables / Sys.Objects Views but how do I correlate to which DB a table belongs to?

The Sys.Databases View list the  databases with their respective Ids. But, the DBID is not part of Sys.Tables / Sys.Objects Views.

Which View will allow me to fetch database to table mappings? 

View 5 Replies View Related

Transact SQL :: Database Constraint Check On Table With Reference Key

Jun 11, 2015

CREATE TABLE PRODUCT_SALES
(
Salesmanid BIGINT,
Productid BIGINT
)

INSERT INTO PRODUCT_SALES (Salesmanid,Productid) VALUES (1,1)
INSERT INTO PRODUCT_SALES (Salesmanid,Productid) VALUES (1,2)
INSERT INTO PRODUCT_SALES (Salesmanid,Productid) VALUES (1,3)

SELECT * FROM PRODUCT_SALES

/* SalesmanID is reference key from Sales Master and ProductID is reference key from Product Master. How should i restrict user through DB with any constraint check, if user tries to enter

INSERT INTO PRODUCT_SALES (Salesmanid,Productid) VALUES (1,2),

It should throw error , if possible user defined message would be more useful.

View 7 Replies View Related

Transact SQL :: Possible To Get Table Relationships Information From Database Diagram?

May 5, 2015

I'm using Sql Server 2012 Enterprise and have a database with over 400 tables. I am looking at one diagram which contains about 20 (or so) tables and their relationships. When I right-click on a relationship line I only see information about which tables are connected on that line but not on which fields.  Can I get that information from the Diagram or can I only get that from the sys tables?

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved