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)
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.
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.
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
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).
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?
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.
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.
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);
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.
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 .
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)
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.
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?
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.
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
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.
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!
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".
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.
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
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 ');
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.
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 = '
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.
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.
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?