SQL Server 2012 :: Create Table From Rows Of A Different Table

Mar 6, 2015

I am using SQL SERVER 2012..I have the following table:

tbtab1
| A | B | C |
| 1 | Pluto | NULL |
| 2 | Pippo | NULL |
| 3 | Rossi | NULL |

I want to creare a new empy table with the columns name contained into the column B of the first table; the following should my results:

tbtab2
| Pluto | Pippo | Rossi |

View 9 Replies


ADVERTISEMENT

SQL Server 2012 :: Stored Procedures Compiles Even When There Is No CREATE TABLE For A Temp Table

Feb 11, 2015

i am inserting something into the temp table even without creating it before. But this does not give any compilation error. Only when I want to execute the stored procedure I get the error message that there is an invalid temp table. Should this not result in a compilation error rather during the execution time.?

--create the procedure and insert into the temp table without creating it.
--no compilation error.
CREATE PROC testTemp
AS
BEGIN
INSERT INTO #tmp(dt)
SELECT GETDATE()
END

only on calling the proc does this give an execution error

View 3 Replies View Related

SQL Server 2012 :: Create New Table From Multiple Table?

Feb 19, 2015

I need to create a table from these 2 tables and want all the data. Table 1 has 15000 records and table has around 1000 records.

I have 2 tables.

SELECT [UniqueID]
,[Company]
,[CustID]
,[CustomerName]
,[FiscYr]

[Code] ....

View 5 Replies View Related

SQL Server 2012 :: Copy A Table With 200 Million Rows To Another Table On Same Server

Aug 11, 2014

I need to use Bulk insert statement for copying a table with 200 million rows to another table on the same server...the table has no primary key or identity column.... script for BULK INSERT ...

View 9 Replies View Related

SQL Server 2012 :: Get Rows And Sum In Joined Table

May 2, 2015

I want to return all rows in table giftregistryitems with an additional column that holds the sum of column `amount` in table giftregistrypurchases for the respective item in table giftregistryitems.

What I tried, but what returns NULL for purchasedamount:

SELECT (SELECT SUM(amount) from giftregistrypurchases gps where registryid=gi.registryid AND gp.itemid=gps.itemid) as purchasedamount,*
FROM giftregistryitems gi
LEFT JOIN giftregistrypurchases gp on gp.registryid=gi.id
WHERE gi.registryid=2

How can I achieve what I need?

Here's my table definition and data:

/****** Object: Table [dbo].[giftregistryitems] Script Date: 02-05-15 22:37:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[giftregistryitems](
[id] [int] IDENTITY(1,1) NOT NULL,

[Code] ....

View 0 Replies View Related

SQL Server 2012 :: Insert Rows In A Table

Jul 28, 2015

In a t-sql 2012 sql script, I have the following script, that only works for a few records since the value of TST.dbo.LockCombination.seq only contains the value or 1 in most cases. Basically for every join listed below, there should be 5 records where each record has a distinct seq value of 1, 2, 3, 4, and 5. Thus my goal is to determine how to add the missing rows to the TST.dbo.LockCombination where there are no rows for seq values of between 2 to 5. I would like to know how to insert the missing rows and then do the following update statement. Thus can you show me the sql on how to add the rows for at least one of the missing sequence numbers?

UDATE LKC
SET LKC.combo = lockCombo2
FROM [LockerPopulation] A
JOIN TST.dbo.School SCH ON A.schoolnumber = SCH.type
JOIN TST.dbo.Locker LKR ON SCH.schoolID = LKR.schoolID AND A.lockerNumber = LKR.number
JOIN TST.dbo.Lock LK ON LKR.lockID = LK.lockID
JOIN TST.dbo.LockCombination LKC ON LK.lockID = LKC.lockID
WHERE LKC.seq = 2

A normal select statement looks like the following:

select * from TST.dbo.Locker LKR
JOIN TST.dbo.Lock LK ON LKR.lockID = LK.lockID
JOIN TST.dbo.LockCombination LKC ON LK.lockID = LKC.lockID
where LKR.number in (000,001,1237)

In case you need the ddl statements for the tables affected here are the ddl statements:

CREATE TABLE [dbo].[Locker](
[lockerID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[schoolID] [int] NOT NULL,
[number] [varchar](10) NOT NULL,
[serialNumber] [varchar](20) NULL,
[type] [varchar](3) NULL,
[locationID] [int] NULL,

[code]...-

View 1 Replies View Related

SQL 2012 :: Unable To Create New Table On Server

May 28, 2015

I used SQL Server 2012 Management Studio to create a new table on an 2014 SQL Server instance and got this message: 'This backend version is not supported to design database diagrams or tables'. Does this mean that I have to have SQL Server 2014 Management Studio to create a table on a SQL Server 2014 instance?

View 1 Replies View Related

SQL Server 2012 :: Insert Rows Into A Table Without Dropping It

Sep 23, 2014

I am finding it difficult to find an example that allows for insertion of additional rows into a table, without dropping the table I'm inserting into. Or inserting specific values. Like this example..

[URL] ....

I have 6 table I am formatting the data to conform to the final table as I'm inserting it into, but none of these examples gives me the example needed. I am using SQL 2012.

<code>
SELECT
CONVERT(VARCHAR(50),[FName]) + ' ' + CONVERT(VARCHAR(50),[LName]) AS [CustName]
,CAST('ALARMCOM' as nvarchar(8)) as VendorName
,CONVERT(VARCHAR(25),[CUSTOMER_CS_ACCOUNT_NUMBER]) AS [Cust_ID]
,CONVERT(VARCHAR(40),[Charge_Description])as [ChargeType]
,CASE

[Code] ....

View 6 Replies View Related

SQL Server 2012 :: Find Rows Where Value In Column Not Found In Another Row In Same Table

Jul 16, 2014

Can't seem to make this SQL query work!

Given one table, Table1, with columns Key1 (int), Key2 (int), and Type (varchar)...

I would like to get the rows where Type is equal to 'TypeA' and Key2 is Null that do NOT have a corresponding row in the table where Type is equal to 'TypeB' and Key2 is equal to Key1 from another row

So, given the data

**KEY1** **Key2** **Type**
1 NULL TypeA
2 5 TypeA
3 1 TypeB
4 NULL TypeA
5 NULL TypeB

I would like to return only the row where Key1 = 4 because that row meets the criteria of Type='TypeA'/Key2=NULL and does not have a corresponding row with Type='TypeB'/Key1=Key2 from another row.

I have tried this and it doesn't work...

SELECT t1.Key1, t1.Key2, t1.Type
FROM Table1 t1
WHERE t1.Key2 IS NULL
AND t1.Type LIKE 'TypeA'
AND t1.Key1 NOT IN
(SELECT Key1
FROM Table1 t2
WHERE t1.Key1 = t2.Key2
AND t1.Key1 <> t2.Key1
AND t2.Type LIKE 'TypeB')

View 2 Replies View Related

SQL Server 2012 :: Merge Multiple Rows From Single Table

Nov 17, 2014

I have resulting rows from a query similar to the following:

The data is coming from a single table that contains only one coverage code column and one coverage code date, but the end user wants the two coverage code types and dates combined into a single row. So the SELECT looks something like this:

SELECT
[Employee ID] = emp.employee_id,
[Coverage Code 1] = enr.coverage_code,
[Coverage Date 1] = enr.coverage_date,
[Coverage Code 2] = case when enr.product_type = 'Accident.Accident'
then enr.coverage_code else NULL end,

[Code] ....

I basically want to merge the like Employee ID's together into a single row like the following:

I know I have done this before and it is probably pretty simple.

View 4 Replies View Related

SQL Server 2012 :: Select Rows With Sum Of Column From Joined Table?

May 2, 2015

I want to return all rows in table giftregistryitems with an additional column that holds the sum of column `amount` in table giftregistrypurchases for the respective item in table giftregistryitems.

What I tried, but what returns NULL for purchasedamount:

SELECT (SELECT SUM(amount) from giftregistrypurchases gps where registryid=gi.registryid AND gp.itemid=gps.itemid) as purchasedamount,*
FROM giftregistryitems gi
LEFT JOIN giftregistrypurchases gp on gp.registryid=gi.id
WHERE gi.registryid=2

How can I achieve what I need?

Here are my table definitions and data:

/****** Object: Table [dbo].[giftregistryitems] Script Date: 02-05-15 22:37:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[giftregistryitems](
[id] [int] IDENTITY(1,1) NOT NULL,

[code].....

View 0 Replies View Related

SQL Server 2012 :: Create A Table That Would Represent Workload For Each Shop

Mar 19, 2015

I am trying to create a table that would represent a workload for each shop. In order to do that I need to have WorkLoad table and ShopWorkLoad table which is actually just aggregation of WorkLoad.

WorkLoad contains a list of following items:

current orders that are in the process (one select statement)
scheduled orders (another select statement)
expected orders (third select statement) that come through a third-party system

All of this needs to be live. So, for example, as soon as order is added to Order table it should be included in WorkLoad if certain conditions are met. Same goes for scheduled orders (which come from another table). Expected orders will be loaded on a daily bases (based on historical data).

ShopWorkLoad table is aggregation of WorkLoad table.

Currently I did it this way:

Added after insert/update trigger on Order table: when order is created/updated, if it meets certain conditions, it should be inserted in WorkLoad, otherwise remove it from workload if it's in there and doesn't meet conditions

Added after insert/update trigger on Schedule table: when order is scheduled, if it meets certain conditions, it should be inserted in WorkLoad, otherwise remove it from workload if it's in there and doesn't meet conditions

Running daily job that populates WorkLoad table with expected orders based on historical values

Final step is to create an indexed view vShopWorkLoad

My biggest concern is usage of triggers which call pretty complex logic to determine whether item should be added to workload or not.

One other option was to create vWorkLoad view and somehow make it an indexed view but currently I don't see a way of doing that because the query consists of 4 union select statements, below is pseudo example. But even if doing it that way, how to build aggregated indexed view on top of vWorkLoad indexed view?

Third option is to use sql agent job which would run every x seconds (maybe 20) and it would execute all of these queries to populate WorkLoad table with delay of 10-20 seconds, but I am still not sure if this is acceptable to the client.

Fourth option is to create 3 or 4 indexed view where sum of them makes a workload. Then, ShopWorkLoad view would be built on top of these 3 or 4 indexed views, but in this case I don't know how this would affect performance since ShopWorkLoad query would be often queried.

Example of workload pseudo query:

select
WorkLoadType = 'Order in process',
OrderId,
ShopId,
...
from
Order

[Code] ....

View 1 Replies View Related

SQL Server 2012 :: Create Table Syntax Dynamically On Run Time

Apr 19, 2015

I am having 100 of flat files need to load in respective staging table.I want to create table on run time as per filename input.suppose if input filename is ABC then table name should be Staging_ABC if file name is XYZ then it should be Staging_XYZ.Table structure is below need to create at run time

CREATE TABLE Staging_'Filename'(
[COL001] [varchar](4000) NULL,
[Id] [int] IDENTITY(1,1) NOT NULL,
[LoadDate] [datetime] NOT NULL default getdate()
)

View 2 Replies View Related

SQL Server 2012 :: Create Table On Given Data Model Diagram

Jul 27, 2015

I never created table on the basis of Data model diagram . I have to create the 3 table on the basis of given Data model diagram. There are 3 tables

1.md_geographyleveltype
2.md_geographylevel
3.md_geographylevelxref

I have tried to create 2 table but unable to create 3rd table. Need to review the script of first 2 table and to create table script for 3rd table.

View 5 Replies View Related

SQL Server 2012 :: How To Delete Duplicate Rows Present In Parent Table

Oct 19, 2014

I have a master table and i need to import the rows into the parent and child table.

Master table name is Flatfile_Inventory
Parent Table name is INVENTORY
Child Tables name are INVENTORY_AMOUNT,INVENTORY_DETAILS,INVENTORY_VEHICLE,
Error details will be goes to LOG_INVENTORY_ERROR

I have 4 duplicate rows in the Flatfile_Inventory which i have already inserted in the Parent and child table.

Again when i run the query using stored procedure,its tells that all the 4 rows are duplicate and will move to the Log_Inventory_Error.

I need is if i have the duplicate rows in the flatfile_Inventory when i start inserting into the parent and child table the already inserted row have the unique ID i must identify it and delete that row in the both parent and chlid table.And latest row must get inserted into the Parent and child table from Flatfile_Inventory.

-- ===============================================================================================
-- STORED PROCEDURE FOR FLATFILE_INVENTORY
-- ===============================================================================================
USE [IconicMarketing]
---=======================================SALES_CURSUR===========================================
--USE IconicMarketing
--GO
DECLARE
@FileType varchar(50) ,
@ACDealerID varchar(50) ,

[code].....

View 2 Replies View Related

SQL Server 2012 :: Convert Rows To Columns Using Dynamic PIVOT Table

Feb 3, 2015

I have this query:

SELECT TOP (100) PERCENT dbo.Filteredfs_franchise.fs_franchiseid AS FranchiseId, dbo.Filteredfs_franchise.fs_brandidname AS Brand,
dbo.Filteredfs_franchise.fs_franchisetypename AS [Franchise Type], dbo.Filteredfs_franchise.fs_franchisenumber AS [Franchise Number],
dbo.Filteredfs_franchise.fs_transactiontypename AS [Transaction Type], dbo.Filteredfs_franchise.fs_franchisestatusname AS [Status Code],

[Code] ....

I need to pivot this so I can get one row per franchiseID and multiple columns for [Franchisee Name Entity] and [Franchise Name Individual]. Each [Franchisee Name Entity] and [Franchise Name Individual] has associated percentage of ownership.

This has to be dynamic, because each FranchiseID can have anywhere from 1 to 12 respective owners and those can be any combination of of Entity and Individual. Please, see the attached example for Franchise Number 129 (that one would have 6 additional columns because there are 3 Individual owners with 1 respective Percentage of ownership).

The question is how do I PIVOT and preserve the percentage of ownership?

View 3 Replies View Related

SQL Server 2012 :: How To Create Staging Table To Handle Incremental Load

Jan 2, 2014

We are designing a Staging layer to handle incremental load. I want to start with a simple scenario to design the staging.

In the source database There are two tables ex, tbl_Department, tbl_Employee. Both this table is loading a single table at destination database ex, tbl_EmployeRecord.

The query which is loading tbl_EmployeRecord is, SELECT EMPID,EMPNAME,DEPTNAME FROM tbl_Department D INNER JOIN tbl_Employee E ON D.DEPARTMENTID=E.DEPARTMENTID.

Now, we need to identify incremental load in tbl_Department, tbl_Employee and store it in staging and load only the incremental load to the destination.

The columns of the tables are,

tbl_Department : DEPARTMENTID,DEPTNAME

tbl_Employee : EMPID,EMPNAME,DEPARTMENTID

tbl_EmployeRecord : EMPID,EMPNAME,DEPTNAME

How to design the staging for this to handle Insert, Update and Delete.

View 9 Replies View Related

SQL Server 2012 :: Insert Multiple Rows In A Table With A Single Select Statement?

Feb 12, 2014

I have created a trigger that is set off every time a new item has been added to TableA.The trigger then inserts 4 rows into TableB that contains two columns (item, task type).

Each row will have the same item, but with a different task type.ie.

TableA.item, 'Planning'
TableA.item, 'Design'
TableA.item, 'Program'
TableA.item, 'Production'

How can I do this with tSQL using a single select statement?

View 6 Replies View Related

SQL Server 2012 :: Insert Rows Based On Number Of Distinct Values In Another Table

May 20, 2014

I have a table with PO#,Days_to_travel, and Days_warehouse fields. I take the distinct Days_in_warehouse values in the table and insert them into a temp table. I want a script that will insert all of the values in the Days_in_warehouse field from the temp table into the Days_in_warehouse_batch row in table 1 by PO# duplicating the PO records until all of the POs have a record per distinct value.

Example:

Temp table: (Contains only one field with all distinct values in table 1)

Days_in_warehouse
20
30
40

Table 1 :

PO# Days_to_travel Days_in_warehouse Days_in_warehouse_batch
1 10 20
2 5 30
3 7 40

Updated Table 1:

PO# Days_to_travel Days_in_warehouse Days_in_warehouse_batch
1 10 20 20
1 10 20 30
1 10 20 40
2 5 30 20
2 5 30 30
2 5 30 40
3 7 40 20
3 7 40 30
3 7 40 40

How can I update Table 1 to see desired results?

View 3 Replies View Related

SQL Server 2012 :: Update Table Based On Existing Values In Multiple Rows?

Oct 1, 2015

The objective is to identify orders where an order fee has been applied incorrectly. I have multiple orders per customer, my table contains an orderID and a customerID. Currently if the customer places additional orders before the previous orders have been closed/cancelled, then additional fees are being applied.

Let's say I'm comparing order #1 to order #2. I need to identify these rows where the following is true:-

The CustID is the same.

Order #2 has a more recent order date.

Order #2 has a FeeDate Before the CancelledDate of Order #1 (or Order #1 has no cancellation date).

So in the table the orderID:2835692 of CustID: 24643 has a valid order fee. But all the subsequently placed orders have fees which were applied before the first order was cancelled and so I want to update the FeeInvalid column with a 'Y'. The first fee will always be valid.

I think I understand why the code I am trying doesn't achieve the result I want but I can't figure out how to write it correctly. Below is one example of code I've tried and also code to create the table and insert some test data.

update t1
SET FeeInvalid = 'Y'
FROM MockData t1 Join MockData t2 on t1.CustID = t2.CustID
WHERE t1.CustID = t2.CustID
AND t2.OrderDate > t1.OrderDate
AND t2.FeeDate > t1.CancelledDate
CREATE TABLE [dbo].[MockData](
[OrderID] [float] NULL,

[code]....

View 4 Replies View Related

How To Create A Table With The Rows For A Table

May 13, 2008

Dear all,
i've table tab1 with columns col1 col2

i've 20 rows out put after selecting the data.

i need all the data of col2 as column for a new table. that is tab2.


please guide me in this regard

Vinod
Even you learn 1%, Learn it with 100% confidence.

View 3 Replies View Related

How To Create SELECT For Rows In Table

Oct 20, 2014

I have two db-tables:

"TAB01" with structure:

CREATE TABLE TAB01 (
ID int NOT NULL,
Name varchar(64) DEFAULT NULL,
PRIMARY KEY (ID)
)

It contains only name of some object.And "TAB02" with structure:

CREATE TABLE TAB02 (
ID int NOT NULL,
TAB01_ID int NOT NULL,
PositionA int,
PositionB int,
StringVal varchar(32) DEFAULT NULL,
PRIMARY KEY (ID)
)

which contains following data:

ID|TAB01_ID|PositionA|PositionB|StringVal|
1|1|1|1|A|
2|1|1|2|B|
3|1|1|3|C|

[code].....

and I need to find a sequence of values in column "StringVal", for example: A B.I look for a suitable SELECT, that returns (in this case) following result:

TAB02.ID|TAB01.Name|TAB02.PositionA|TAB02.PositionB|
1|ABC|1|1|
10|DEF|2|3|
25|JKL|4|3|
30|MNO|5|1|
36|MNO|5|7|
41|PQR|6|4|
46|STU|7|2|

Data inserted in "TAB02" represents real-life structure:

ID|Name|P01|P02|P03|...|Pxy|
1|ABC|A|B|C|D|E|A|D|
2|DEF|J|K|A|B|F|F|B|
3|GHI|B|A|C|A|F|G|A|F|
4|JKL|F|E|A|B|B|E|E|
5|MNO|A|B|C|B|A|D|A|B|
6|PQR|D|E|F|A|B|A|F|
7|STU|A|A|B|B|E|B|E|

View 1 Replies View Related

Create Table With 15,000,000 Default Rows

Jul 23, 2005

Hi I want to create a table with one column, which is a identitycolumn.Let's say like this:CREATE TABLE DefaultTable(N int identity(0,1))Then I want to fill this table with 15,000,000 records, so that I havea table with the numbers 0 to 14,999,999.How can I do this as fast as possible. A standard INSERT would take along time.(It can be a temp table or a table variable. I just need a list withnumbered 0 to 15,000,000)Thank you.Gidon

View 2 Replies View Related

Create Script To Insert 200 Rows Into Table

Aug 15, 2007

I have to create a script to install a database, and one of the tableshas about 200 rows of static data... I dont want to have to manuallytype in 200 insert statements, so is there a better way to do this? Ithought about maybe exporting the data into a CSV file and using somesort of procedure to insert the records that way... Any advise?

View 6 Replies View Related

SQL 2012 :: Create A Table

Nov 1, 2014

How to code to create a table in which there are 300 columns and name them as column1, column2...column300? All data type is varchar(255)

View 3 Replies View Related

SQL 2012 :: How To Select Top 200 To 300 Rows From A Table

Mar 9, 2015

Select top 100 * from tab1 order by col1 ---gives me the top 100 order by col1

Select top 200 * from tab1 order by col1 ---gives me the top 200 order by col1

How do I select the top 100 to 200

View 3 Replies View Related

SQL Server 2012 :: Create View With Exploding Rows Into Multiple

Apr 28, 2014

I have a table like below:

ItemIdAmountTax1Tax2SrvType
111 100 10 20 1
112 200 10 2
113 300 10 30 3

Now I want to create View that will have an exploded resultset based on SrvType.

For SrvType 1 and 2 there will be 2 lines per Itemid - One for 'Amount' anod another for 'Tax1+Tax2'. But for SrvType 3 there will be 3 lines per 'ItemId' - one for 'Amount', one for Tax1 and another for 'Tax2'.

I have a few hundred source records like this. Now sure how to achieve the exploded resultset with a View.

View 4 Replies View Related

SQL 2012 :: Create Primary Key On A Table?

Apr 22, 2014

In what situations we can create primary key on a table? I mean what is the minimum no of rows we can prefer to create PK.

View 8 Replies View Related

SQL 2012 :: Create A Table Using Value Of A Variable

May 14, 2014

create a table using the value of a variable

example:
create uspCreateTable
@ NameTable varchar (10)
the
begin
create table @ NameTable (
id int,
Name varchar (20))
end

the intention is to create a procedure that creates tables changing only the name.

View 9 Replies View Related

SQL 2012 :: Table (with Zero Rows) Not Returning Any Result

Jun 26, 2014

I am trying to run queries on a table (table has zero rows). Inspite of giving 0 rows returned the query keeps on running and I have to cancel it. I tried inserting a dummy row into the table but even the insert operation is taking too long.Every query which I hit on the table just keeps on running without giving any result.

But this is not the case with other tables in the database.They are all running fine giving proper results. But this one table is behaving funny.

View 3 Replies View Related

SQL 2012 :: Count Rows When Making New Table

Jan 8, 2015

How can I count the rows when I make new table. Here is my code:

SELECT EMPLOYEE_ID, LAST_NAME, SALARY, JOB_ID, COMMISSION_PCT, DEPARTMENT_ID, COUNT(TO_CHAR(HIRE_DATE, 'DAY')) AS NUM_EMPLOYEES
FROM EMPLOYEES
WHERE TO_CHAR(HIRE_DATE, 'Day') = 'Monday'
GROUP BY EMPLOYEE_ID, LAST_NAME, SALARY, JOB_ID, COMMISSION_PCT, DEPARTMENT_ID;

Here is the table: [URL] ....

I have 10 rows, so I would like under NUM_EMPLOYEES to be displayed 10 on each row.

View 5 Replies View Related

SQL 2012 :: How Many Rows Warrant Need For Index On A Table

Sep 30, 2015

What is the threshold that warrants the need for creating an index on a table. I have a system with a TABLE that has only 500 rows, very static, but accessed many many times. The cardinality from the statistics of Actual vs. Estimate rows is off by only 5 rows. I have all clustered index scans. What I need to be looking for as I tune this DB. I am going through every stored procedure to finely tune the DB I am supporting.

View 4 Replies View Related

SQL Server 2008 :: Create A Table Valued Function That Fetch Through The Table?

Apr 24, 2015

I would like to create a table valued function that fetch through the table below using a cursor and return the records that are unique

EmpidChDateSiteuseridinitsal finsalNote
-------------------------------------------- ----------
236102015-4-21 22:02:10.8072570 0.696176161 change inisal value
236112015-4-21 22:02:11.0502570 0.696176161change inisal value
236122015-4-21 22:02:11.1202570 0.696176161 change inisal value
236132015-4-21 22:02:11.2452570 0.696176161change inisal value

View 9 Replies View Related







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