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
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
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.
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:
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.
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
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
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.
I realise this may be a very simple question for most of you, but if you can help this could save me a ton of work. Yes, I am a newbie. I need to create a database and bulk insert data. The format for the table is set as an html file, the schema file is set as a txt file, and the data is in the form of a text file. I can see that this should be simple, but I just can't get the syntax right. I have tried writing a simple query to do this and have read and re-read the appropriate microsoft pages but still no luck - not for the want of trying. What I want to do is eventually manipulate the data from Visual Basic. I tried doing all this firstly via Visual Basic, then via MySQL and finally decided that seting up a database via Microsoft SQL ought to be the easiest way to go since it can easily be accessed via Visual Basic. Any help will be appreciated.
I have just one table but need to create a trigger that takes place after an update on the Orders table. I need it to multiply two columns and populate the 3rd column (total cost) with the result as so:
I know the word 'With' is a SQL Reserved; I created a SQL Script Generator that creates insert statements to copy data from one SQL Server database to another. If a row contains the word 'with' or 'With' the insert statement fails. Is there a way around this? The script is executed in the Query Analyzer window of SQL Server.
The record below is an example of a row that fails.
Insert Into [Contact] ([Active],[AddressID],[Birthday],[Birthmonth],[ContactType],[CreatedBy],[CreatedDate],[Description],[Employed],[FirstName],[HasResume],[LastName],[MiddleName],[ModifiedBy],[ModifiedDate],[Personality],[RowVersion])
Values ('False', 0, 0, 0, 1, 0, '', 'Wants to get back with Van Halen', 'False', 'David', 'False', 'Roth', 'Lee', '', '', '', '')
The error message shown is:
Incorrect syntax near the keyword 'with'. If this statement is a common table expression or an xmlnamespaces clause, the previous statement must be terminated with a semicolon.
I have a Table with Financial Data in it and for Certain Accounts (the Key Field is actindx Column)there is no data for Certain Months.
I need a query to fill in the data for each Calendar_Month. This should look at the actindx column and Calendar_Month column if there is no data for a specific Month for that actindx I want it to copy all columns for that actindx and insert into a new row, but just puts Zero Dollars for ActivityDebit, ActivityCredit, and NetAmount.
I have created a CalendarMonth_Lookup Table. I assume there is a way to outer Join the two and insert rows or use an "IF" ,"THEN" type of Statement and just manually add the Calendar Month data.
I am including all the code to make the tables and Insert Data into them.
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?
help on CREATE stored procedure delete and after insert where not exist in one stored procedure in table_B
Code Snippet CREATE PROCEDURE [dbo].[delete_from_table_B] @empID varchar(500) as DELETE FROM table_B WHERE charindex(','+CONVERT(varchar,[empID])+',',','+@empID+',') > 0
---HELP from this ponit how to insert ? after where not exist
IF @@ROWCOUNT > 0
BEGIN
insert into table_B set (empID,ShiftDate,shiftType) where not exist
I need to create about 1,000 (literately) Excel files that each contain 5 tabs. The data being placed on the tabs will always be the same (meaning the columns are static). I am fairly advanced at Excel VBA so I can write code that does all the following in Excel (looped 1,000 times):
Open an Excel template
Bring data in from the tables
Filter, then copy-paste the appropriate rows into each tab.
Save the new Excel file.
Email the file to appropriate individual (it is a Microsoft Exchange Server). As I started this in VBA, I thought that I might be able to do it with SSIS. My concern is I need to have the rows formatted (font, border, etc.) and the number of rows change.
My questions are: Is it possible to format Excel with SSIS? Can I email the files even if it is not with an SMTP protocol? Would SSIS process this data faster then Excel? Does this approach even make sense? Am I better just doing it with VBA?
I have a create user wizard. On the created user event. I am calling a datasource.insert to insert the email, userid, and opt in to newsletter option into another table. For some reason it is inserting the value twice into the database. I have checked possibilities for why this might be happening. I am pulling my hair out. Any ideas? Andrew
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):
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.
I have never used triggers before and I have tried to solve one problem. If I have the column "currency" in a table and want to make sure that the entered value i valid in relation to another table that contains valid currency formats, I did it like this:
--------------------------------- CREATE TRIGGER [trigger_checkCurrency] ON [dbo].[Client] FOR INSERT, UPDATE AS declare @currency as char(50) declare @country as char(50)
declare cur cursor for SELECT currency, country FROMinserted
OPEN cur fetch cur into @currency, @country WHILE @@FETCH_STATUS = 0 BEGIN if not exists(select * from listinfoid where listname = 'currency' and listid = @currency) begin set @currency = (cast(@currency as varchar (3)) + ' is not a valid currency') CLOSE cur DEALLOCATE cur RAISERROR (@currency,16,-1) with log return end if not exists(select * from listinfoid where listname = 'country' and listid = @country) begin set @country = (cast(@country as varchar (3)) + ' is not a valid contry') CLOSE cur DEALLOCATE cur RAISERROR (@country,16,-1) with log return end else fetch cur into @currency, @country
END CLOSE cur DEALLOCATE cur update Client set currency = UPPER(currency), country = UPPER(country) ---------------------------------
I use a cursor to handle multiple rows in an update query. (SQL2000-server)
Is there an easier och better way to do this? I´m a bit unsure of this code.
I am looking high and low for some assistance with developing a VB .NET solution that I programmatically create a package and add tasks. I am adding a BULK INSERT task to load large FLAT TEXT files into SQL Server 2005 tables. When I execute the application I execute a package validation and it always returns FAILURE. I have been reading and searching like crazy and I have bought 2 microsoft books, TO NO AVAIL! Can anyone PLEASE help me with this. Thank you!
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')
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', )
I was using Visual Studio 2003 and SQL Server CE 2.0 for C# mobile applications. The .sdf database were created in the emulator or in the mobile device itself using Query Analizer.
The application developed need some initial data to run, and this data is obtained executing one service that reads a postgree database, and insert the data in the SQL CE database of the mobile device. But, given the size of the database (maybe 10.000 rows), it tooks too much time (sometimes 6 hours).
Now we are migrating to Visual Studio 2005 and SQL Server 2005 Mobile Edition.
I want to know if its possible to create the .sdf database and load the data into this database on the desktop. Maybe through the execution of a .sql script, or through a service executed on the desktop.
After this, its just upload de .sdf file to the mobile device.
how to do this i have table of employee ,evry employee have a unique ID "empid" empid VAL_OK -------------------------- 111 0 222 0 333 0
now insert multiple insert to my work_table shifts for all month for evry employee like this (this is work_table) empid date val -------------------------------------------------- 111 01/02/2008 1 111 02/02/2008 2 ............... 111 29/02/2008 5 --next employee 222 01/02/2008 1 222 02/02/2008 4 ............... 222 29/02/2008 6 --next employee 333 --next employee 444 --next employee 555 -------------------------------------------------------------
now i need for evry OK insert (for all month) each employee go to the TB_Employee and update each employee once !! from VAL_OK=0 to VAL_OK=1 like this
empid VAL_OK -------------------------- 111 1 222 1 333 1 ---------------------- like this i know who is the employee have shift for all month and who NOT !
i think it like this
Code Snippet Create trigger for_insert on tb_work For insert begin if @@rowcount = 1 Update tb_employee Set val_ok= 1
else /* when @@rowcount is greater than 1, use a group by clause */ Update tb_employee set val_ok= 1 select empid from tb_work group by tb_work.empid
Can I roll back certain query(insert/update) execution in one page if query (insert/update) in other page execution fails in asp.net.( I am using sqlserver 2000 as back end) scenario In a webpage1, I have insert query into master table and Page2 I have insert query to store data in sub table. I need to rollback the insert command execution for sub table ,if insert command to master table in web page1 is failed. (Query in webpage2 executes first, then only the query in webpage1) Can I use System. Transaction to solve this? Thanks in advance
Hello, I recently view a webcast of sql injection, and at this moment I created a user, and give dbo to this user, and this same user, is the one I have in the connection string of my web application, I want to create a user to prevent sql injection attacks, I mean that user wont be able to drop or create objects, only select views, tables, exec insert,update, deletes and exec stored procedures.
Is any easy way to do this?
A database role and then assing that role to the user?
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.
I use ODBC driver to perform SQLServer commands from C/C++ application.
An "INSERT INTO <table> (<column>) VALUES (NULL)" command has a random behavior in a SQL2000 Server running on WindowsXP.
The <column> in this command has 2 definitions about the NULL value :
- the NULL is accepted in the table definition, with <column> ut_oui_non NULL".
- the NULL is rejected in the type definition, with EXEC sp_addtype ut_oui_non, 'char(1)', 'NOT NULL' and a rule to check values with '0' or '1'
1/ The column definition in any explorer show the NULL from table deffinition
2/ The "INSERT INTO" is completed in SQL Query tool, used on Windows2000 and WindowsXP computers, connected to the same SQL2000 server.
3/ The "INSERT INTO" is completed in the application, running on Windows2000 with an ODBC driver to the same SQL2000 server.
4/ The "INSERT INTO" is rejected in the application, running on WindowsXP witjh an ODBC driver to the same SQL2000 server. The error 513 means that INSERT VALUES conflicts with previous rule. So only the type definition seems to be used.
But :
5/ This is a random error, and some INSERT with the same values in this column are completed.
6/ This random error seems to be discarded by using the "Use NULLs, paddings and warnings ANSI" checkbox in the ODBC driver user source configuration.
This checkbox is only use for enforcing the ANSI syntax in SQL commands, and has no known effect on type checking.
Do you know about any conflict of column NULL value between a type definition and a table definition ?