How To Create INSERT Query For Contents Of Table

Oct 5, 2007

Using Sql Server 2005 Express and Management Studio I need to create
a SQL insert statement for the contents of a table (FullDocuments) so
that I can run the query on another server with that same table schema
(FullDocuments) and the contents will automatically be inserted into
the new instance of the FullDocuments table.
In Management Studio
I have used "Script Table as" for the create table query.  The
second instance of FullDocuments has been created on the remote
server.  Now how do I generate an insert query for the contents of
FullDocuments so that the contents can be moved/inserted to the new
instance of the table?
Thanks for any help provided. 
 

View 10 Replies


ADVERTISEMENT

Create A Table Of Contents Based On Report Items From A List Control

Apr 28, 2008

What are the options to create a table of contents based on the report items in a List Control? Document Mapping works for online viewing. A table of content would make the report easier to read when it's printed.

Any help is much appreciated. Thanks.

View 1 Replies View Related

Perform A Query That Will Merge Contents Of Various Table

Aug 27, 2012

I am trying to perform a query in SQL that will merge the contents of various table, using search criteria to narrow down the results. All of the tables have the exact same fields, and the search criteria is the same for all of them. What I am looking for is the most efficient way to perform this. I am using SQL stored procedures, and passing the results into my code. Note that in my real-world scenario there are more than three tables.

1) Merge all the tables into one and then perform the search criteria:
SELECT a, b, c FROM
(SELECT a, b, c FROM Table1
UNION ALL
SELECT a, b, c FROM Table2
UNION ALL
SELECT a, b, c FROM Table3) AS MY_MERGE
WHERE {SEARCH CRITERIA}

2) Perform the search criteria on each table and merge the results
SELECT a, b, c FROM
(SELECT a, b, c FROM Table1 WHERE {SEARCH CRITERIA}
UNION ALL
SELECT a, b, c FROM Table2 WHERE {SEARCH CRITERIA}
UNION ALL
SELECT a, b, c FROM Table3 AS MY_MERGE WHERE {SEARCH CRITERIA})

View 3 Replies View Related

Default Table Owner Using CREATE TABLE, INSERT, SELECT && DROP TABLE

Nov 21, 2006

For reasons that are not relevant (though I explain them below *), Iwant, for all my users whatever privelige level, an SP which createsand inserts into a temporary table and then another SP which reads anddrops the same temporary table.My users are not able to create dbo tables (eg dbo.tblTest), but arepermitted to create tables under their own user (eg MyUser.tblTest). Ihave found that I can achieve my aim by using code like this . . .SET @SQL = 'CREATE TABLE ' + @MyUserName + '.' + 'tblTest(tstIDDATETIME)'EXEC (@SQL)SET @SQL = 'INSERT INTO ' + @MyUserName + '.' + 'tblTest(tstID) VALUES(GETDATE())'EXEC (@SQL)This becomes exceptionally cumbersome for the complex INSERT & SELECTcode. I'm looking for a simpler way.Simplified down, I am looking for something like this . . .CREATE PROCEDURE dbo.TestInsert ASCREATE TABLE tblTest(tstID DATETIME)INSERT INTO tblTest(tstID) VALUES(GETDATE())GOCREATE PROCEDURE dbo.TestSelect ASSELECT * FROM tblTestDROP TABLE tblTestIn the above example, if the SPs are owned by dbo (as above), CREATETABLE & DROP TABLE use MyUser.tblTest while INSERT & SELECT usedbo.tblTest.If the SPs are owned by the user (eg MyUser.TestInsert), it workscorrectly (MyUser.tblTest is used throughout) but I would have to havea pair of SPs for each user.* I have MS Access ADP front end linked to a SQL Server database. Forreports with complex datasets, it times out. Therefore it suit mypurposes to create a temporary table first and then to open the reportbased on that temporary table.

View 6 Replies View Related

SSMS Express: Create TABLE && INSERT Data Into Table - Error Msgs 102 && 156

May 18, 2006

Hi all,

I have SQL Server Management Studio Express (SSMS Express) and SQL Server 2005 Express (SS Express) installed in my Windows XP Pro PC that is on Microsoft Windows NT 4 LAN System. My Computer Administrator grants me the Administror Privilege to use my PC. I tried to use SQLQuery.sql (see the code below) to create a table "LabResults" and insert 20 data (values) into the table. I got Error Messages 102 and 156 when I did "Parse" or "Execute". This is my first time to apply the data type 'decimal' and the "VALUES" into the table. I do not know what is wrong with the 'decimal' and how to add the "VALUES": (1) Do I put the precision and scale of the decimal wrong? (2) Do I have to use "GO" after each "VALUES"? Please help and advise.

Thanks in advance,

Scott Chang

///////////--SQLQueryCroomLabData.sql--///////////////////////////
USE MyDatabase
GO
CREATE TABLE dbo.LabResults
(SampleID int PRIMARY KEY NOT NULL,
SampleName varchar(25) NOT NULL,
AnalyteName varchar(25) NOT NULL,
Concentration decimal(6.2) NULL)
GO
--Inserting data into a table
INSERT dbo.LabResults (SampleID, SampleName, AnalyteName, Concentration)
VALUES (1, 'MW2', 'Acetone', 1.00)
VALUES (2, 'MW2', 'Dichloroethene', 1.00)
VALUES (3, 'MW2', 'Trichloroethene', 20.00)
VALUES (4, 'MW2', 'Chloroform', 1.00)
VALUES (5, 'MW2', 'Methylene Chloride', 1.00)
VALUES (6, 'MW6S', 'Acetone', 1.00)
VALUES (7, 'MW6S', 'Dichloroethene', 1.00)
VALUES (8, 'MW6S', 'Trichloroethene', 1.00)
VALUES (9, 'MW6S', 'Chloroform', 1.00)
VALUES (10, 'MW6S', 'Methylene Chloride', 1.00
VALUES (11, 'MW7', 'Acetone', 1.00)
VALUES (12, 'MW7', 'Dichloroethene', 1.00)
VALUES (13, 'MW7', 'Trichloroethene', 1.00)
VALUES (14, 'MW7', 'Chloroform', 1.00)
VALUES (15, 'MW7', 'Methylene Chloride', 1.00
VALUES (16, 'TripBlank', 'Acetone', 1.00)
VALUES (17, 'TripBlank', 'Dichloroethene', 1.00)
VALUES (18, 'TripBlank', 'Trichloroethene', 1.00)
VALUES (19, 'TripBlank', 'Chloroform', 0.76)
VALUES (20, 'TripBlank', 'Methylene Chloride', 0.51)
GO
//////////Parse///////////
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near '6.2'.
Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'VALUES'.
////////////////Execute////////////////////
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near '6.2'.
Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'VALUES'.

View 7 Replies View Related

Create Insert Query

Aug 7, 2005

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[INSQUERY]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[INSQUERY]
GO

CREATE TABLE [dbo].[INSQUERY] (
[Query] [varchar] (8000) COLLATE Arabic_CI_AS NULL
) ON [PRIMARY]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[KS]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[KS]
GO

CREATE TABLE [dbo].[KS] (
[IDCOL] [int] IDENTITY (1, 1) NOT NULL ,
[COLU] [varchar] (50) COLLATE Arabic_CI_AS NULL ,
[Datatype] [varchar] (100) COLLATE Arabic_CI_AS NULL ,
[Value] [varchar] (8000) COLLATE Arabic_CI_AS NULL
) ON [PRIMARY]
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateInsQryEx]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CreateInsQryEx]
GO

----------------------------------

CREATE PROCEDURE [dbo].CreateInsQryEx @Tablename varchar(50) = NULL, @SelectPart varchar(7500) = '*', @FilterPart varchar(7500) = NULL
AS
TRUNCATE TABLE INSQUERY
DECLARE @QUERY VARCHAR(7500)
DECLARE @ROW int, @NROW int
DECLARE @DATATYPE varchar(20)
SET @NROW = 1
DECLARE @COL int, @nCOL int
DECLARE @VALUE varchar(7500)
DECLARE @SELECTPART1 VARCHAR(7500)
IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].[KSINSERTQRY]') AND OBJECTPROPERTY(ID, N'ISUSERTABLE') = 1)
DROP TABLE [DBO].[KSINSERTQRY]

SET NOCOUNT ON
DECLARE @InsQuery varchar(7500)
IF(@TableName IS NULL)
BEGIN
RAISERROR ('TableName Cannot be Blank', 16, 1)

END

SELECT @Query = 'SELECT ' + @SelectPart + ' INTO KSINSERTQRY FROM ' + @TableName
IF(@FilterPart IS NOT NULL)
BEGIN
SELECT @Query = @Query + ' WHERE '+@FilterPart
END
EXEC(@Query)

Alter Table KSINSERTQRY Add ICOL int IDENTITY (1,1 )
TRUNCATE TABLE KS

INSERT INTO KS (COLU,Datatype)
SELECT '['+COLUMN_NAME+']',DATA_TYPE from INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'KSINSERTQRY'

SELECT @ROW = COUNT(*) FROM KSINSERTQRY
WHILE (@NROW <= @ROW)
BEGIN
SET @SELECTPART1 = NULL
SELECT @COL = COUNT(*) FROM KS
SET @NCOL = 1

DECLARE @COLNAME varchar(50)
SET @InsQuery = 'INSERT INTO ' + @TableName + ' '
IF(@SelectPart <> '*')
BEGIN
SET @InsQuery = @InsQuery + '(' + @SelectPart + ')'
END

SET @InsQuery = @InsQuery + 'VALUES ('
WHILE (@NCOL < = @COL)
BEGIN
SELECT @COLNAME = COLU,@DATATYPE = datatype FROM KS WHERE IDCOL = @NCOL
SET @QUERY = 'UPDATE KS SET [VALUE] = (SELECT CONVERT(VARCHAR(7500),' +
+ @COLNAME + ') FROM KSINSERTQRY WHERE ICOL = ' +
convert(varchar(3),@NROW) +') WHERE COLU = ''' + @COLNAME + ''''
--SELECT @Query
EXEC(@QUERY)

SELECT @VALUE = Convert(Varchar(7500),[VALUE]) FROM KS WHERE COLU = @COLNAME

SET @VALUE = CASE @Datatype when 'varchar' then '''' + '''' + @VALUE + '''' + ''''
when 'nvarchar' then '''' + '''' + @VALUE + '''' + ''''
when 'text' then '''' + '''' + CONVERT(VARCHAR(7500),@VALUE) + '''' + ''''
when 'char' then '''' + '''' + @VALUE + '''' + ''''
when 'nchar' then '''' + '''' + @VALUE + '''' + ''''
when 'smalldatetime' then '''' + '''' + @VALUE + '''' + ''''
when 'datetime' then '''' + '''' + @VALUE + '''' + '''' ELSE @VALUE END
SET @QUERY = 'UPDATE KS SET [VALUE] = '+ '''' + Convert(Varchar(7500),@VALUE) + ''' WHERE COLU = ''' + @COLNAME + ''''
EXEC(@QUERY)
SET @NCOL = @NCOL +1
END
SELECT @SELECTPART1 = COALESCE(@SELECTPART1 + ',', ' ') + ISNULL(CONVERT(VARCHAR(5000),[VALUE]),'NULL') FROM KS WHERE RTRIM(LTRIM(COLU)) <> '[ICOL]'
--SELECT @SELECTPART1
SET @InsQuery = @InsQuery + @SELECTPART1 + ')'
INSERT INTO INSQUERY VALUES (@InsQuery)
SET @NROW = @NROW + 1
END
SELECT * FROM INSQUERY



Kapil Arya

View 7 Replies View Related

Checking Contents Of Column And Replacing Contents If First Character Is A Letter

Jun 25, 2007

Hi All,I have come up against a wall which i cannot get over.I have an sql db where the date column is set as a varchar (i know, should have used datetime but this was done before my time and i've got to work with what is there). The majority of values are in the format dd/mm/yyyy. However, some values contain the word 'various'.I'm attempting to compare the date chosen on a c# .net page with the values in the db and also return all the 'various' values as well.I have accomplished casting the varchar to a datetime and then comparing to the selected date on the .net page. However, it errors when it comes across the 'various' entrant.Is there anyway to carry out a select statement comparing the start_date values in the db to the selected date on the .net page and also pull out all 'various' entrants at the same time without it erroring? i thought about replacing the 'various' to a date like '01/01/2010' so it doesn't stumble over the none recognised format, but am unsure of how to do it.This is how far i have got: casting the varchar column to datetime and comparing.  SELECT * FROM table1 WHERE Cast(SUBSTRING(Start_Date,4,2) + '/' + SUBSTRING(Start_Date,1,2) + '/' +SUBSTRING(Start_Date,7,4) as datetime)  '" + date + "'"Many thanks in advance! 

View 7 Replies View Related

Can Sql Server Read An Outside File And Insert The Contents Into The Database?

Aug 8, 2000

hello!

i'm an sql server beginer. i was wondering if some of you guys can help
me out. i need for the sql server to be able to read an outside file (just text) and be able to run a script that will insert it in the database. it's a dcc output file. we've tried running this script:

DROP TABLE tests
go
DECLARE @SQLSTR varchar(255)
SELECT @SQLSTR = 'ISQL -E -Q"dbcc checkdb(master)"'
CREATE TABLE tests (Results varchar(255) NOT NULL)
INSERT INTO tests EXEC('master..xp_cmdshell ''ISQL -E -Q"dbcc checkdb(master)"''')


and it's running good but the problem is the results of the dbcc here did not come from a file but directly after executing the dcc command. is there a way to do it?

thank's for the help!

View 1 Replies View Related

SQL Tools :: BCP And BULK INSERT To Copy Complete Database Contents?

Jan 29, 2015

Script: [URL] ....

I need to move all of the contents of one database into anther with the same schema, and it looks like this might be just what I need. But it is from 2007, so I wonder if it is still current?

Also, having tried to run it on another database to generate the script that will actually do the copying, I have a few questions. It looks like it generates statements to import the data twice. For example:

BULK INSERT [TaPerfGDB].[dbo].[i1]
   FROM 'C:Tempi1.Dat'
   WITH (FORMATFILE = 'C:Tempi1.FMT',
         BATCHSIZE = 1000000,
         ERRORFILE = 'C:TempBI_i1.ERR',
         TABLOCK);

And a little later:

INSERT INTO [TaPerfGDB].[dbo].[i1]
    SELECT *
      FROM  OPENROWSET(BULK  'C:Tempi1.Dat',
      FORMATFILE='C:Tempi1.Xml'
      ) as t1;

That does not really make any sense to me. It also generates statements like this:

bcp "[TaPerfGDB].[dbo].[GDB_GEOMNETWORKS]" format nul -n -CRAW -f "C:TempGDB_GEOMNETWORKS.fmt" --S"PGALLUCC-M7" -T

What is the deal with the double hyphen by the servername? Won't it just see that as a comment? It can be easily fixed, but I am just suprised that it is still there after all these years. My purpose in doing this is a desparate attempt to salvege a database that sits on a server with multiple drive errors. These prevent backups, so I cannot just restore the database on the new server. That is why I want to try an approach that goes table by table, so that at least all the tables which are not touched by the drive errors can be moved.

It is a 3 TB database running on SQL Server 2008 R2 std. ed.

View 2 Replies View Related

Create And Insert To Table

Sep 26, 2005

This is probably a simple question, but have searched and haven't found an answer. Basically I have a query that creates a table, but due to row length, need to narrow down the field sizes.

Here is my current stored procedure that creates the big table from a query, (I Have condensed the query for example purposes). This creates a new table.


SELECT tbl_Officer.GOID, tbl_Assignment.AssignmentID, tbl_Officer.YG, tbl_Officer.Branch, tbl_Officer.Nickname
INTO NEWTABLE
FROM tbl_Officer INNER JOIN tbl_Assignment ON tbl_Assignments.GOID= tbl_Officer.GOID
WHERE tbl_Officer.Status ='Active'
ORDER BY tbl_Officer.LastName;


I have been able to create the new table first, Like this:

CREATE TABLE NEWTABLE
(
GOID int,
IDPosition int,
YG nvarchar(5),
Branch nvarchar(5),
Nickname nvarchar(20
)

Now how can I use the same query above to popluate this new table? Also in the above create table how do I set the GOID as a primary key?

Thanks for your help

View 1 Replies View Related

Create Table, Insert Into

Nov 18, 2005

I was having an issue summing up the clientcred.defmonthlypayment column on a user by user basis when I was joining it with another table to get only "active" objects. It would return exponentially large numbers when joined to the other table. So I was trying to drop it into a temp table so i could query against it to get the results I needed. But it keeps telling me that 'null' values arent allowed in the 'clientid' column when I instucted it to put the results into another column and to allow 'null' values in that column.

error message at the bottom

-------------------------------------------------------------

CREATE TABLE #accts (
clientid int primary key,
clientid1 varchar(6)null,
monthlyacctpayment varchar(10)null,
grp1 int null,
clientid2 varchar(6)null,
monthlyacctfees varchar(10)null,
grp2 int null
)

INSERT into #accts
(clientid1,monthlyacctpayment,grp1)
SELECT distinct clientcred.clientid as 'clientid1',
CAST(sum(clientcred.defmonthlypayment) as varchar)'monthlyacctpayment',
GROUPING(clientcred.clientid) 'grp1'
FROM clientcred
GROUP BY clientcred.clientid WITH ROLLUP


INSERT into #accts
(clientid2,monthlyacctfees,grp2)
SELECT clients.clientid as 'clientid2',
CAST(sum(clients.monthlyacctfee) as varchar)'monthlyacctfees',
GROUPING(clients.clientid) 'grp2'
FROM clients
GROUP BY clients.clientid WITH ROLLUP


Select clients.clientid,monthlyacctfees,monthlyacctpayment from #accts,clients
where clients.active='-1' and clients.clientid=#accts.clientid

drop table #accts

--------------------------------------------------------------
Results

Server: Msg 515, Level 16, State 2, Line 14
Cannot insert the value NULL into column 'clientid', table 'tempdb.dbo.#accts______________________________________________________________________________________________________________00000001CFA5'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Server: Msg 515, Level 16, State 2, Line 23
Cannot insert the value NULL into column 'clientid', table 'tempdb.dbo.#accts______________________________________________________________________________________________________________00000001CFA5'; column does not allow nulls. INSERT fails.
The statement has been terminated.


Why is it trying to drop the requested info into the clients column when I state that it should be dropped into the specified column?

I apologize for any statements or references that are wrong now but thats why I posted in the 'new to SQL Server' section. Thanks everyone

View 8 Replies View Related

Scripts To Insert Or Create Table

Jan 24, 2006

i am executing this scripts in sql server2000

SELECT
'INSERT into temp values(data1, data2, data3)' +
'SELECT ' +
CONVERT(VARCHAR(20), temp2.data1) + ', ' + CONVERT(VARCHAR(20), temp2.data2) + ', ' + '''' + CONVERT(VARCHAR(20), temp2.data3) + ''''
FROM temp, temp2
order by temp2.data1


now my table temp and temp2 both has folowing fields and data type

data1 int
data2 int
data3 varchar(20)

befor execution i have 0 records in temp and 10 records in temp2.
this scripts supposed to add all 10 records from temp2 to temp but it does nothing. evevn it is not giving error too.

View 4 Replies View Related

Create Insert Scripts For Existing Table?

Jan 6, 2007

What is the easiset way to create TSQL Insert scripts for each record in a table. Can this be accomplished with one of the tools in SQL Server 2005?

Thanks in advance

View 5 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

Wants To Insert Into Multiple Table By A Single Insert Query

Apr 11, 2008

Hi,ALL
I wants to insert data into multiple table within a single insert query
Thanks

View 3 Replies View Related

MS SQL CREATE TABLE/INSERT INTO Wierd Issue - Going Bald

Sep 11, 2004

Yes, I am pulling my hair out on this one...................

PROBLEM:When importing from my .sql file, I loose many lines of info in my SQL table. I am using the SQL Query Analyzer to execute the file. The file contains 655,000 rows and 20 columns of data on it.

When I run the full file, the system tells me it does not have enough system resources to execute the request. I broke it down just to see if it could handle a smaller file.

When I create a table and have it insert 10,000 rows of info, it drops 88 lines of data.

When I do the same with 120,000 rows I loose 300 rows of data.

When I run it with 56,000 lines of data on the file, I loose 260 rows of data.

When I do just 1,000 rows or below it is perfect.

I have taken the chunks into Excel and verified the number of lines I was trying to put into the table, and everytime, it showed I had the amount of lines I thought I was trying to import.

When I did a query once the table was created to see how many lines it created, I was always short.

This is what my query consisted of (Let me know if this may be my issue)

SELECT COUNT(*) Col_1
FROM nfo_tablename
GO

I even tried zero column names

Any suggestions??? Am I doing something wrong here? Should I be executing the process in a different way?

Here is the basic idea of what the top part of my "CREATE TABLE" file looks like (Color coded as I see it in my Query Analyzer):


Code:


CREATE TABLE nfo_tablename(
Col_1 Numeric,
Col_2 Character(4),
Col_3 Character(11),
Col_4 Character(25),
Col_5 Character(6),
Col_6 Character(5),
Col_7 Character(3),
Col_8 Character(6),
Col_9 Character(22),
Col_10 Character(2),
Col_11 Character(10),
Col_12 Numeric,
Col_13 Character(9),
Col_14 Character(2),
Col_15 Character(2),
Col_16 Character(2),
Col_17 Character(8),
Col_18 Character(1),
Col_19 Character(25),
Col_20 Character(39),
Col_21 varchar);
insert into nfo_tablename values(1,'DSW','UNIT','002-11-K','','57C','840','674209','PCD W/OVRLY DTI/DTM','P','ESPECIAL',674856,'676--9','CO','','1','','1','0201-11','Manufacturer_Name','T');
insert into nfo_tablename values(2,'DSW','SHELF','002-07','','35C','9','09','UNEQUAL','M','',0,'','CO','','','','1','002-07','Manufacturer_Name','T');



Thank you all for your insight. Any ideas, thoughts or suggestions, would be appreciated. I really need to get this table done so I can get a couple web pages created this weekend that are due Monday.

View 1 Replies View Related

CREATE TABLE For BULK INSERT: How To Set The Decimal Number Right In Col ?

Jan 26, 2008

Hi all,

I executed the following sql code in my SQL Server Management Studio Express (SSMSE):
-- myCSV1.sql --

USE MyDatabase

GO

CREATE TABLE myCSVtable

(

Col1 int,

Col2 nvarchar(25),

Col3 nvarchar(25),

Col4 decimal (9.3),

)

BULK INSERT myCSVbulk

FROM 'c:myfile.csv'

WITH

(

FIELDTERMINATOR = ',',

ROWTERMINATOR = ''

);

GO
=====================================
I got the following error message:


Msg 102, Level 15, State 1, Line 6

Incorrect syntax near '9.3'.

How can I set the statement "Col4 decimal (9.3)" right? Please help and advise.

Thanks in advance,
Scott Chang

View 7 Replies View Related

Trying To Create A Proc That Will Insert Values Based On A Condition That Is Another Table

Feb 16, 2005

Can someone give me a clue on this. I'm trying to insert values based off of values in another table.

I'm comparing wether two id's (non keys in the db) are the same in two fields (that is the where statement. Based on that I'm inserting into the Results table in the PledgeLastYr collumn a 'Y' (thats what I want to do -- to indicate that they have pledged over the last year).

Two questions

1. As this is set up right now I'm getting NULL values inserted into the PledgeLastYr collumn. I'm sure this is a stupid syntax problem that i'm overlooking but if someone can give me a hint that would be great.

2. How would I go about writing an If / Else statement in T-SQL so that I can have the Insert statement for both the Yes they have pledged and No they have not pledged all in one stored proc. I'm not to familar with the syntax of writing conditional statements within T-SQL as of yet, and if someone can give me some hints on how to do that it would be greatly appriciated.


Thanks in advance, bellow is the code that I have so far:

RB



Select Results.custID, Results.PledgeLastYr
From Results, PledgeInLastYear
Where Results.custID = PledgeInLastYear.constIDPledgeInLastYear
Insert Into Results(PledgeLastYr)
Values ('Y')

View 1 Replies View Related

SQL 2012 :: Automatically Create Insert Statements For Table Data

Jun 10, 2014

How to create insert statements of the data from a table for top 'n' rows. I know we can create using generate scripts wizard, but we can't customize the number of rows. In my scenario i got a database with 10 tables where every table got millions of records, but the requirement is to sample out only top 10000 records from each table.

I am planning to generate table CREATE statements from GENERATE Scripts wizard and add this INSERT STATEMENT at the bottom.

EX : INSERT [dbo].[table] ([SERIALID], [BATCHID] VALUES (126751, '9100278GC4PM1', )

View 4 Replies View Related

Transact SQL :: Create Hierarchies Table Or Query From Multi Parent Table?

May 21, 2015

convert my table(like picture) to hierarchical structure in SQL. actually i want to make a table from my data in SQL for a TreeList control datasource in VB.net application directly.

ProjectID is 1st Parent
Type_1 is 2nd Parent
Type_2 is 3rd Parent
Type_3 is 4ed Parent

View 13 Replies View Related

Query Hightest Value Contents Of Each Folder?

Jul 20, 2005

Hi,Can anyone tell me how to select the "most recent" date values from agrouped query? Consider the following:CREATE TABLE [dbo].[TestQuery] ( [ID] [int] NOT NULL , [ID_Parent] [int] NOTNULL , [Date] [datetime] NOT NULL ) ON [PRIMARY]This is a simplified adjacency list. What I want to do is find the highestvalued item by date for each sub-tree. In other words, the single highestdate item when This.ID_Parent = That.ID_Parent. I think I first need togroup by ID_Parent, then select the TOP 1 from this query, but how toaggregate them so I get the TOP 1 for each ID_Parent?Thanks for any help you can give me,Robin

View 3 Replies View Related

How To Create A Make-Table Query With A Union Query

Oct 30, 2006

I have successfully execute a union query. How can i create a make-table query to accomodate the resultset of the union query?

View 2 Replies View Related

Print Table Contents

Jul 19, 2006

Hello

I want to have a print of table records in sql server express.

I went several locations, but File|Print item didn't on.

How can i print table contents in sql express environment ?

Thank you for helping me.

View 3 Replies View Related

Create Package For Multiple Table Insert From Flat File Source

Feb 23, 2008



Hello Guys,

I am working in one company and currently I am assigned to new project for Data Migration from company X to our company Y using SSIS. I am totally new and i just completed 5 tutorial which was gien on MSDN website.

Basically client is going to send us first flat file with 1 million records with Header, Detail and Trailer records.
I want to create a Package in such a way that it dumps all this first load into 7 to 8 different tables at a time.
we also have to include functionlity for validation and error check.
On successfull load error file should only return Header and Trailer but no detail records.
If there are any errors then error file should contain Header, Detail records which were unable to load plus trailer which we have to sent back to client.

When 2nd file comes that time we have to check whether this is new records or change (update) one depending on Flag which tells it.


This is basically high level idea of my Package what i need to create. If u guys have any question then let me know.

I know you guys are very experienced one. Anyone of you please give me some detail idea on it I would really appricate it.
I have very limited time line for it.

Thanks

Shah

View 4 Replies View Related

Move A Table (and Its Contents!) To Another Database

Jan 23, 2007

 
Hi,
I am relatively new to this stuff.
I am using Microsoft SQL Server Management Studio Express  (9.00.1399.00)
Can someone tell me the way to get a table and its content to another database (I use two at webhosts4life)
Or perhaps a way to export the data of a table so I can do it at a later stage.
 
Is that at all possible with this program or do I have to use the non-express version?
 
Thanks in advance,
Lex
 

View 4 Replies View Related

Looping Thru A Table And Updating The Contents

Nov 8, 2007

Hello, Its hard trying to explain this.
I have 3 tables
Table 1 is where the users are stored, each user has a username and a userrank
Table 2 is where the points that decides the userrank are stored
Table 3 contains the available userranks like this
 
Table 1 (user_list) looks briefly like this:username nvarchar(20),userrank int, -- Reference to Table3 id... alot more fields
Table 2 (settings_profile) looks like this:username nvarchar(20),total_active_points int,... some more fields
Table 3 (data_ranks) looks like this:id int primary key auto inc,rankname nvarchar(20),min_pts int,max_pts int
 
Points get added to table 2 whenever they do something that generates points on the site. Points also get withdrawn every 7 days, so a user can only collect points for 7 days, on the 8th day, all points he earned on the 1st day is reduced from the current points with this code:
WHILE (SELECT @username = username, @id = id, @temp1 = ap_sentmails, @temp2 = ap_createdthreads, @temp3 = ap_createdanswers, @temp4 = ap_signguestbook, @temp5 = ap_blogcomment, @temp6 = ap_createblogentry, @temp7 = ap_profilefirsttime, @temp8 = ap_profilephoto, @temp9 = ap_activateguestbook, @temp10 = ap_addnewfriend, @temp11 = ap_superguruvote, @temp12 = ap_forumtopicvote, @temp13 = ap_labervote, @temp14 = ap_funstuffitemvote, @temp15 = ap_movievote, @temp16 = ap_actorvote, @temp17 = ap_money_new WHERE (created < Dateadd(dd, -7, @todaysdate))BEGINSET @sum = 0SET @sum = @temp1 + @temp2 + @temp3 + @temp4 + @temp5 + @temp6 + @temp7 + @temp8 + @temp9 + @temp10 + @temp11 + @temp12 + @temp13 + @temp14 + @temp15 + @temp16 + @temp17UPDATE settings_profile SET total_active_points = total_active_points - @sum WHERE (username = @username)DELETE FROM konto_daylist WHERE (id = @id)END
Now my question is this, i want to loop thru the table A, collect all usernames inside of it, then run it against table b and table c to determine the current rank of the user.Something like this...
DECLARE @username nvarchar(20)DECLARE @pts int, @rank int
...something that starts a loop thru table A (user_list) and get the username into @username...
SELECT @pts = total_active_points  FROM settings_profile WHERE (username = @username)-- Determine the rank here, by compairing the points the user have against the pointstabel in table data_ranksSELECT @rank = id FROM data_ranks WHERE (pts_min => @pts AND pts_max < @pts)UPDATE user_list SET rank = @rank WHERE (username = @username)
...next persion in the loop...
This SP runs once a day and will first reduce the points from 8days ago, then it will run thru all the users and determine their new rank...
But how do i loop thru all the users? with a cursor?

View 10 Replies View Related

Updating /replacing Contents Of The Table

Jun 11, 2007

Is it possible to do an update * where in we update all the contents of the table after selecting specific rows of the same table.

for ex:

create table #Result(rowid int identity(1,1),cust_no int,companyname varchar(100),address varchar(200),zip varchar(9));

insert into #Result(cust_no,companyname,address,zip)
where (customertype='r' and customer.comp_id ='11')
group by customer.cust_no, customer.company


select * from #Result where customerstatus='s';

after this i want to update/replace the #Result with whatever results I have from the select statment.

Thanks for your replies.

View 5 Replies View Related

How DO I Generate A Table Of Contents For A Report??

Aug 28, 2006

Hi!!!

Can anybody help me with the generation of Table of Contents for a report using SQL Server 2005 Reporting Services. Let me ellaborate. The scenerio is...i m having a report of lets say 500 pages grouped on employees, showing the performance of each employee between specific date range. Now if the manager prints the report of 500 pages he will be more intersted to jump directly to a perticular employee's page which means my printed report had to have a Table of Contents on my grouped criteria (which in this case is employee number). I would really appriciate if someone can suggest me a solution for this.

View 10 Replies View Related

Building Dynamic Query Based On Dropdownlist Contents

Feb 18, 2008

Thanks in advance for taking the tiemt o read this post:
 
I am workingon an application in vb.net 2008 and I have 5 drop down lists on my page.
I have code that worked in .net 2005 for my databind but would like to use new features in 08 to do this same thing.
Here is my 05 code how would I do this same things in 08?
 Dim db As New DataIDataContext
Dim GlobalSQLstr As String
GlobalSQLstr = "select Orig_City, ecckt, typeflag, StrippedEcckt, CleanEcckt, ManualEcckt, Switch, Vendor, FP_ID, order_class, Line_type, id from goode2 where 1=1"
If (ddlOrigCity.SelectedValue <> "") Then
GlobalSQLstr &= "and Orig_City = '" & ddlOrigCity.SelectedValue & "'"
End If
If (ddlSwitch.SelectedValue <> "") Then
GlobalSQLstr &= "and switch = '" & ddlSwitch.SelectedValue & "'"
End If
If (ddlType.SelectedValue <> "") Then
GlobalSQLstr &= "and Order_Class = '" & ddlType.SelectedValue & "'"
End If
If (ddlFormatType.SelectedValue <> "9") Then
GlobalSQLstr &= "and typeflag = '" & ddlFormatType.SelectedValue & "'"
End If
If (ddlVendor.SelectedValue <> "") Then
GlobalSQLstr &= "and Vendor = '" & ddlVendor.SelectedValue & "'"
End IfDim AllSearch = From A In db.GoodEcckts2s
If (ddlErrorType.SelectedValue <> "0") Then
GlobalSQLstr &= "and ErrorType = '" & ddlErrorType.SelectedValue & "'"
End IfDim cmd As New SqlClient.SqlCommand
Dim rdr As SqlClient.SqlDataReaderWith cmd.Connection = New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString1").ConnectionString)
.CommandType = Data.CommandType.Text
.CommandText = GlobalSQLstr
.Connection.Open()
rdr = .ExecuteReaderMe.gvResults.DataSource = rdrMe.gvResults.DataBind()
.Connection.Close()
.Dispose()End With
 
 
 

View 4 Replies View Related

How Do I List Contents Of File Directory In The SQL Query Analyzer

Apr 13, 2006

how do I list contents of file directory in the SQL Query Analyzer

View 1 Replies View Related

Using An Exec Query To Insert Pdf, .doc File Into Table From A Dir Path Which Is A Field In Another Table

Aug 5, 2007

I have the following query in sql 2005:


PROCEDURE [dbo].[uspInsert_Blob] (

@fName varchar(60),

@fType char(5),

@fID numeric(18, 0),

@bID char(3),

@fPath nvarchar(60)

)



as

DECLARE @QUERY VARCHAR(2000)

SET @QUERY = "INSERT INTO tblDocTable(FileName, FileType, ImportExportID, BuildingID, Document)

SELECT '"+@fName+"' AS FileName, '"+@fType+"' AS FileType, " + cast(@fID as nvarchar(18)) + " as ImportExportID, '"+@bID+"' AS BuildingID, * FROM OPENROWSET( BULK '" +@fPath+"' ,SINGLE_BLOB)

AS Document"

EXEC (@QUERY)

This puts some values including a pdf or .doc file into a table, tblDocTable.

Is it possible to change this so that I can get the values from a table rather than as parameters. The Query would be in the form of: insert into tblDocTable (a, b, c, d) select a,b,c,d from tblimportExport.

tblImportExport has the path for the document (DocPath) so I would subsitute that field, ie. DocPath, for the @fPath variable.

Otherwise I can see only doing a Fetch next from tblIportExport where I would put every field into a variable and then run this exec query on these. Thus looping thru every row in tblImportExport.

Any ideas how to do this?

View 1 Replies View Related

Reading And Editing Sql Server 6.5 Table Contents

Aug 17, 2000

What is the best way to read and edit data in the tables of a sql server 6.5 database?

Thanks

Gunnar
gunnardl@yahoo.com

View 1 Replies View Related

DB Engine :: Delete All Remote Table Contents

Jun 24, 2015

I'm copying date from a  sql server 2000 table to a sql server 2008 R2 table using a Linked Server.I need to be sure the remote table is correct before processing it.I first delete all the remote table contents and after that, I insert into remote_table from local_tableWhat happens if the communication is interrupted during the insert?I mean, Can I be sure all records were copied just checking if record count > 0 ?

View 3 Replies View Related







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