--This procedure will generate the Structure of a table
Create Procedure GenerateScript (
@tableName varchar(100))
as
If exists (Select * from Information_Schema.COLUMNS where Table_Name=@tableName)
Begin
declare @sql varchar(8000)
declare @table varchar(100)
declare @cols table (datatype varchar(50))
insert into @cols values('bit')
insert into @cols values('binary')
insert into @cols values('bigint')
insert into @cols values('int')
insert into @cols values('float')
insert into @cols values('datetime')
insert into @cols values('text')
insert into @cols values('image')
insert into @cols values('uniqueidentifier')
insert into @cols values('smalldatetime')
insert into @cols values('tinyint')
insert into @cols values('smallint')
insert into @cols values('sql_variant')
set @sql=''
Select @sql=@sql
+case when charindex('(',@sql,1)<=0 then '(' else '' end +Column_Name + ' ' +Data_Type +
case when Data_Type in (Select datatype from @cols) then '' else '(' end
+case when data_type in ('real','money','decimal','numeric') then cast(isnull(numeric_precision,'') as varchar)+
','+case when data_type in ('real','money','decimal','numeric') then cast(isnull(Numeric_Scale,'') as varchar)
end when data_type in ('char','nvarchar','varchar','nchar') then cast(isnull(Character_Maximum_Length,'') as varchar) else '' end
+case when Data_Type in (Select datatype from @cols)then '' else ')' end
+case when Is_Nullable='No' then ' Null,' else ' Not null,' end
from Information_Schema.COLUMNS where Table_Name=@tableName
select @table= 'Create table ' + table_Name from Information_Schema.COLUMNS where table_Name=@tableName
select @sql=@table + substring(@sql,1,len(@sql)-1) +' )'
select @sql as DDL
End
Else
Select 'The table '+@tableName + ' does not exist'
Hello everybody,I was configuring a SqlDataSource control using SQL Authentication mode.I first added a database file (testdb.mdf) through Solution Explorer-Add New Items. Then through Database Explorer I created a table named "info"Then while configuring the SqlDataSource control I used the SQL Authentication mode and attached the "testdb.mdf" database file.Test Connection showed success. But when I hit the Ok button of the wizard it displayed the following error message:Failed to generate a user instance of SQL Server. Only an integrated connection can generate a user instance.While configuring the SqlDataSource control I clicked "New Connection". Under Data Source section I tried both Microsoft SQL Server and Microsoft SQL Server Database File. And in both the cases I attached a databese file(testdb.mdf). Plz enlighten me on this.Thanks and Regards,Sankar.
Hi! When MS published starter kits there were files .sql in App_Data. This files contained some sample data for a DB. How to create such files when I have database with data ? Jarod
One of my first tasks on my current project was to generate all of the SQL scripts needed to rebuild the database. Of course, one of the catches was that everything needed to be separated out (table columns in different script from PKs different from FKs different from DEFAULTs, etc., etc.). And we wanted our own comment block inserted. So, I couldn't just use the Generate SQL Script from Enterprise Manager and be done with it. I was going to need to do some more work. Well, here's one of the scripts I wrote to build the FK scripts. Execute this script, then copy & paste the results into a new window. Break apart into separate .sql files as desired.
NOTE: Be sure to show results in Text (not grid) and change the display options in QA to return more than just 256 characters.
/*************************************************************************************************** Author: Mark Caldwell Date: 11/15/2002 Descrip: Generate scipt commands to ADD FOREIGN KEY CONSTRAINTS for constraints already in DB.
NOTE: Be sure to set your Tools/Options/Results/Maximum Characters per column to a large enough number (such as 2000) to display the entire command. ***************************************************************************************************/
SELECT '---------------------------------------------------------------------------------------------------- -- ' + so2.name + ' to ' + so3.name + ' ---------------------------------------------------------------------------------------------------- IF OBJECTPROPERTY(OBJECT_ID(N''' + so1.name + '''), ''IsForeignKey'') = 1 BEGIN ALTER TABLE ' + so2.name + ' DROP CONSTRAINT ' + so1.name + ' PRINT '' -- DRP - ' + so1.name + ''' END G' + 'O
' FROM sysforeignkeys sfk JOIN sysobjects so1 on sfk.constid = so1.id JOIN sysobjects so2 on sfk.fkeyid = so2.id JOIN sysobjects so3 on sfk.rkeyid = so3.id JOIN INFORMATION_SCHEMA.COLUMNS ISC1 on so2.name = ISC1.TABLE_NAME AND sfk.fkey = ISC1.ORDINAL_POSITION JOIN INFORMATION_SCHEMA.COLUMNS ISC2 on so3.name = ISC2.TABLE_NAME AND sfk.rkey = ISC2.ORDINAL_POSITION ORDER BY so2.name
The web site I am building is working fine locally, but I am hitting some problems with setting it up on a remote hosting server.First off, how can I generate the sql script to populate the SQL db on the remote server?I am using VS 2005 Standard. Do I need to d/l the SQL Server Express?Once I get that going, I should be able to figure out the rest...but I'll prolly have another question or two.Thanks
i need to auto generate the user id in id colunm in my sqldatabase table.i want it to generate in this fashion.(mycompanyname-todaydate-number.)eg (ibm-15thfeb-1) (ibm-15thfeb-2) (ibm-16thfeb-1)here i need this user id to be automatically displayed in my web form when doing registration of new user,then only after clicking the savebutton i want all the data along with user id to be inserted into the table in sqldatabase.thanksjack.
Hi, I have a question, I have created a table and with a primary key called "ID". However, I want the "ID" be auto increment as well. when inserting new record into the database.I'm using vb.net. how can I do in the following format: "1", "2", "3", ............ etc. I've the code below but it's not working in the right way, what's wrong with my code? Private Sub BtnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click Dim ssql As String Dim Itemid As Integer Dim updcmd As SqlClient.SqlCommand Itemid = 0 mysqladap = New SqlClient.SqlDataAdapter("select MAX(Item_id) From auction where item_type= '" & (Image1.ImageUrl) & "'", mySqlConn) Itemid = (Itemid) + 1 ssql = "insert into auction (item_id,owner_name,owner_mail,owner_mobile,owner_phone,owner_ext,item_type,item_name,item_image,item_desc,item_cost,start_date) values ('" & (Itemid) & "','" & Trim(ownertxt.Text) & "' ,'" & Trim(emailtxt.Text) & "', '" & Trim(mobiletxt.Text) & "', '" & Trim(phonetxt.Text) & "','" & Trim(exttxt.Text) & "','" & Trim(DropDownList1.SelectedValue) & "','" & Trim(itemtxt.Text) & "','" & Trim(Image1.ImageUrl) & "','" & Trim(desctxt.Text) & "','" & Trim(costtxt.Text) & "','" & Trim(Today.Date) & "')" updcmd = New SqlClient.SqlCommand(ssql, mySqlConn) updcmd.ExecuteNonQuery() lblmsg.Visible = True End SubAnyone can help me? Thanks.
I want to transfer some procedures using a generated script. However, the procedures that create pre-existing tables will not be created. Is there a way to shut off the validation so that I can create these procedures without getting errors?
Is there a way to write a dts package that will Generate SQL Scripts for a particular database? I am just learning dts and would like to automate this process that I run on weekly basis.
how to generate txt file from sql table. I want text file with respective columns without any seperator between columns. and if for an example a column of int having 5 digits but i want it in text file with 10 digits with remaining all as blanks. guide me how to do this. thnks in adv
This is my first time on sqlteam forum so a big hello to everyone!!
Firstly I am very noive user of sql to say the least, but i have be requested to create a .txt file
Its for a program that will read the txt file i create to produce a letter i.e I will be extracting, TITLE, FORENAME, SURNAME etc
MR JOE BLOGGS
Here is the my code so far, like i said i am a very novice user so try to help me and not condem me for my lack of knowledge!
SELECT LPA_INPUT.INPUT_TITLE, LPA_INPUT.INPUT_SURNAME, LPA_HISTORY.LPA_AMT, LPA_HISTORY.ELIG_RATE, LPA_HISTORY.RATE_REBATE, LPA_HISTORY.RR_AMT, LPA_HISTORY.LPA_APPLIC, LPA_HISTORY.LPA_AMT FROM LPA_HISTORY, LPA_INPUT WHERE LPA_HISTORY.CLAIM_NO = LPA_INPUT.CLAIM_NO ---------------------------------------------------- Iv been asked to have these eight fields looping over and over for all the records in the database, So im not to how to do that and how to generate it in a txt file?!
i recently moved from sql server 7 to sql 2005 -- in sql 7 if i wanted to generate an sql script then It would generate a whole script --- in sql 2005 - when i do generate it seems to attach a file -- I want to generate a script that I can then modify and use to create a new db -- is this possible?
I was thinking of creating a custom generated IDs for my table. I would like the ID to be something like "HR001" or "IT001", the two letter prefix would indicate the dept it belongs to. Initially I thought of having a table that will hold all the seed values for the IDs but I realize that this could have some concurrency problems if there will be a multiple number of users are creating a record at the same time. So now I have totally no idea on how to deal with the concurrency problem.
I will not be using this as a primary key because I already have the Identity field to be my primary key, though of course this field would definitely be unique. I will just be using this to display in the UI.
Hi, Do someone know if there is a SP_ or XP_ function for help me create a script of create table? I can do it "on-line" by right click a table in Enterprise-Manager (all properties;generate sql-script), but I want to "call a command" to do this. Very glad if someone know! //Lotta
is there any easy way I can take a select statment (such as select from payments where datetime>'20071122' and output a sql insert statment for these records?
I basically need to move a specific set of records from one sql server to another (both sql server 2005) any suggestions for the best way to do this?
The table in the database has a field called LabID. That field is aninteger and consists of the year plus a counter. For example, thefirst record of 2006 would be "20060001," the second record of 2006would be "20060002" and so on. I'm trying to create an Insert triggerthat can generate the ID value when a new record is inserted, but I'mnot quite sure how to implement that trigger. Can anyone help?
Hello,I want to generate a SQL Script of a SQL Server database. To do this, Iright-click the database name and choose the option All Tasks/GenerateSQL Script.Than I get a text file with a script that generates all objects, but theorder in which the objects are generated is wrong. There are a lot ofviews in the database and many views are based on other views. When Itry to execute the script on a different computer, I get a lot of errormessages, because the script tries to create views that are based onother views that are not created yet.Is there a way to generate a script that automatically 'knows' whichviews to create first or do I have to manually look through all viewsand find out myself the execute order? (I hope not, because it arereally a lot of views).Greetings,Chris*** Sent via Developersdex http://www.developersdex.com ***
I have a table PCRel(ParentChildRelationship) with two columns PCRel(ParentId int,ChildId int) I have to generate the value for the column ChildId based upon max(ChildId)+1 for a ParentId. My requirement is to do it at table level since data is inserted into table from flatfiles also. So I cannot put this logic in SProc but I have to put it at table level. What is the best way to do this?
I use MS SQL Server 2005 I have done some changes in a Database in my machine. I need to copy the changes to the Windows 2003 Server SQL Server. The changes include (DCL includes new ones as well as alter ones) Both the machines of Text indexing on certains fields.
How to I generate a good script for smooth running. (thats which attributes to choose on Generate Scriptsor copy in some other way)
Hi ... there was a cool feature in sql 2k for exporting scripts for stored procedures. i.e
for eg if I had 3 procedures.
prc_proc1
prc_proc2
prc_proc3
and if I want 2 export the script of these sp's to 3 individual files rather than one single file then I was able to chose in SQL2000
i.e I was able to create 3 files with the same name as the sp's
prc_proc1.sql
prc_proc2.sql
prc_proc3.sql
Now I want 2 do the same thing in SQL 2005,but its allowing me to create one single file... Pls tell me how to generate scripts for individual stored procedures.
I would like to know if it is possible to generate an error when the value of a field is null. In my case, I do a right outer join between 2 tables (in a ole db source) and if the left id is null i want to stop the package in error (I use a conditional split to know if the id is null or not). How can I stop in error my package ? I thought I could use a lookup to do that but I have too many data: after 10 minutes, there is still no data reaching the lookup.
Hi guys.Im using a gridview to show some training data on my website which is populated by:<asp:SqlDataSource ID="ARENATraining" runat="server" ConnectionString="<%$ ConnectionStrings:ARConnection %>" SelectCommand="SELECT [EventType], [CourseLink], [EventDate], [EventTitle], [EventLocation], [EventWebsite] FROM [qry_FutureEvents] WHERE ([EventPrivate] = @EventPrivate) ORDER BY [EventDate]"> <SelectParameters> <asp:Parameter DefaultValue="FALSE" Name="EventPrivate" Type="Boolean" /> </SelectParameters> So far so good..However I want to be able to filter the data.A) Show everythingB) Show individual EventType i.e. Seminar, Training etc etcIs it possible to generate the Select Command via a function? (im not using stored procedures for this part of the site, nor really want to at the moment). Id appreciate any help, otherwise ill be forced to curse and swear and use the good ol repeater and figureing out how to page it! Cheers guys
HI All, I use MSSQL as my database and ASP.NET as my front application. I want to display Price value S$23.68. The dayatype I used is smallmoney, but it display: S$23.6800. HOw do I control the number of decimals point in the column of MSSQL?? Thanks a lot Suigion
HiI'm developing a website using SQL Server Express 2005 and VIsual Web Developer Express, and now want to start testing my website in a live environment. Until now I have been manually creating tables on my web database to match those on my local DB, but I have so many tables I don't want to manually recreate them all again. Is there a method in SQL Server Express 2005 that will allow me to generate insert scripts for all the tables? CheersAndy