473,654 Members | 3,190 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

To create store procedure

1 New Member
want to create store procedure that. want to send the table name as argument and retrive the data of that argument. and want to store data in temperary table using the insert query.

HERE I AM ATTACHING A SAMPLE PROCEDURE IT WAS NOT WORKING PERFECTLY. HELP ME


--exec SP_Generate_Ins ert_Statements tbl_Attachment, 1
--select * from tbl_Attachmentt esting
--exec SP_Generate_Ins ert_Statements tbl_Attachmentt esting,1

ALTER PROCEDURE [dbo].[SP_Generate_Ins ert_Statements_ Testing]
@strTableName varchar(128), -- used to specify the table to generate data for
@RequiredGo bit = 0 -- used to allow GO statements to separate the insert statements
AS

--Variable declarations
DECLARE @InsertStmt varchar(max)
DECLARE @Fields varchar(8000)
DECLARE @SelList varchar(max)
DECLARE @ColName varchar(128)
DECLARE @IsChar tinyint
DECLARE @tableData varchar(8000)
DECLARE @strImageSQL varchar(200)
DECLARE @strTextSQL varchar(200)
DECLARE @ImageData varbinary(8000)
DECLARE @TextData varchar(max)

DECLARE @bitIdentity BIT

SET NOCOUNT OFF

SELECT @bitIdentity = OBJECTPROPERTY( OBJECT_ID(TABLE _NAME), 'TableHasIdenti ty')
FROM INFORMATION_SCH EMA.TABLES
WHERE TABLE_Name =@strTableName

PRINT '---- ** Start of Inserts ** ----'
PRINT ''

IF @bitIdentity = 1
BEGIN
PRINT 'SET IDENTITY_INSERT [' + @strTableName +'] ON '
END

--initialize variables
SELECT @InsertStmt = 'INSERT INTO [' + @strTableName + '] (',
@Fields = '',
@SelList = 'SELECT '


--create a cursor that loops through the fields in the table
--and retrieves the column names and determines the delimiter type that the field needs
DECLARE CR_Table CURSOR FAST_FORWARD FOR

SELECT COLUMN_NAME,
'IsChar' = CASE
WHEN DATA_TYPE in ('int', 'money', 'decimal', 'tinyint', 'smallint' ,'numeric', 'bit', 'bigint', 'smallmoney', 'float','timest amp') THEN 0
WHEN DATA_TYPE in ('char', 'varchar', 'nvarchar','uni queidentifier', 'nchar') THEN 1
WHEN DATA_TYPE in ('datetime', 'smalldatetime' ) THEN 2
WHEN DATA_TYPE in ('text', 'ntext') THEN 3
WHEN DATA_TYPE in ('sql_variant') THEN 4
WHEN DATA_TYPE in ('image') THEN 5
ELSE 6
END
FROM INFORMATION_SCH EMA.COLUMNS c WITH (NOLOCK)
INNER JOIN syscolumns sc WITH (NOLOCK)
ON c.COLUMN_NAME = sc.name
INNER JOIN sysobjects so WITH (NOLOCK)
ON sc.id = so.id
AND so.name = c.TABLE_NAME
WHERE table_name = @strTableName
AND DATA_TYPE <> 'timestamp'
AND sc.IsComputed = 0
ORDER BY ORDINAL_POSITIO N
FOR READ ONLY
OPEN CR_Table

FETCH NEXT FROM CR_Table INTO @ColName, @IsChar

WHILE (@@fetch_status <> -1)
BEGIN

IF @@fetch_status <> -1
BEGIN
IF @SelList = 'SELECT'
BEGIN
SELECT @Fields = @Fields + '[' + @ColName + ']' + ', '
SELECT @SelList = CASE @IsChar
WHEN 1 THEN @SelList + ' ISNULL('''''''' + REPLACE(['+ @ColName + '],'''''''', '''''''''''' ) + '''''''',''NULL '') ' + ' COLLATE database_defaul t + '
WHEN 2 THEN @SelList + 'ISNULL(''''''' ' + CONVERT(VARCHAR (20),['+ @ColName + '])+ '''''''',''NULL '') ' + ' COLLATE database_defaul t + '
WHEN 3 THEN @SelList + ' ISNULL('''''''' + REPLACE(CONVERT (VARCHAR(MAX),['+ @ColName + ']),'''''''', '''''''''''')+ '''''''' ,''NULL'') '+ ' COLLATE database_defaul t + '
--WHEN 3 THEN @SelList + ''' CONVERT(VARCHAR (MAX),['+ @ColName + ']) '''
WHEN 4 THEN @SelList + ' ISNULL('''''''' + REPLACE(CONVERT (VARCHAR(8000),['+ @ColName + ']),'''''''', '''''''''''')+ '''''''' ,''NULL'') '+ ' COLLATE database_defaul t + '
WHEN 5 THEN @SelList + '''MyImageData' ''''
ELSE @SelList + ' ISNULL(CONVERT( VARCHAR(2000),['+ @ColName + '],0),''NULL'')' + ' COLLATE database_defaul t + ' END
END
ELSE
BEGIN
SELECT @Fields = @Fields + '[' + @ColName + ']' + ', '
SELECT @SelList = CASE @IsChar
WHEN 1 THEN @SelList + ''',''' + ' + ' + ' ISNULL('''''''' + REPLACE(['+ @ColName + '],'''''''', '''''''''''' ) + '''''''',''NULL '') ' + ' COLLATE database_defaul t + '
WHEN 2 THEN @SelList + ''',''' + ' + ' + 'ISNULL(''''''' ' + CONVERT(VARCHAR (20),['+ @ColName + '])+ '''''''',''NULL '') ' + ' COLLATE database_defaul t + '
WHEN 3 THEN @SelList + ' ISNULL('''''''' + REPLACE(CONVERT (VARCHAR(MAX),['+ @ColName + ']),'''''''', '''''''''''')+ '''''''' ,''NULL'') '+ ' COLLATE database_defaul t + '
--WHEN 3 THEN @SelList + ''' CONVERT(VARCHAR (MAX),['+ @ColName + ']) '''
WHEN 4 THEN @SelList + ''',''' + ' + ' + ' ISNULL('''''''' + REPLACE(CONVERT (VARCHAR(8000),['+ @ColName + ']),'''''''', '''''''''''')+ '''''''' ,''NULL'') '+ ' COLLATE database_defaul t + '
WHEN 5 THEN @SelList + ''',''' + '''MyImageData' ''''
ELSE @SelList + ''',''' + ' + ' + ' ISNULL(CONVERT( VARCHAR(2000),['+@ColName + '],0),''NULL'')' + ' COLLATE database_defaul t + ' END
END

IF @IsChar = 5
SET @strImageSQL = 'SELECT ' + @ColName + ' FROM ' + @strTableName
END

FETCH NEXT FROM CR_Table INTO @ColName, @IsChar
END

CLOSE CR_Table
DEALLOCATE CR_Table

SELECT @Fields = SUBSTRING(@Fiel ds, 1,(len(@Fields)-1))
SELECT @SelList = SUBSTRING(@SelL ist, 1,(len(@SelList )-1))
SELECT @SelList = @SelList + ' FROM ' + @strTableName
SELECT @InsertStmt = @InsertStmt + @Fields + ')'


SET NOCOUNT ON

--now we need to create and load the temp table that will hold the data
--that we are going to generate into an insert statement

CREATE TABLE #TheData (TableData varchar(MAX))
INSERT INTO #TheData (TableData) EXEC (@SelList)

IF @strImageSQL <> ''
BEGIN
CREATE TABLE #ImageData (TableData image)
INSERT INTO #ImageData (TableData) EXEC (@strImageSQL)
END

--Cursor through the data to generate the INSERT statement / VALUES
DECLARE CR_Data CURSOR FAST_FORWARD FOR SELECT TableData FROM #TheData FOR
READ ONLY

OPEN CR_Data
FETCH NEXT FROM CR_Data INTO @tableData

IF @strImageSQL <> ''
BEGIN
DECLARE CR_ImageData CURSOR FAST_FORWARD FOR SELECT TableData FROM #ImageData FOR
READ ONLY
OPEN CR_ImageData
FETCH NEXT FROM CR_ImageData INTO @ImageData
END


WHILE (@@fetch_status <> -1)
BEGIN
IF (@@fetch_status <> -2)
BEGIN

IF @strImageSQL <> ''
BEGIN
PRINT @InsertStmt
PRINT 'VALUES '
PRINT '('
PRINT SUBSTRING(@tabl eData,1,CHARIND EX('MyImageData ',@tableData)-2)
PRINT @ImageData
PRINT SUBSTRING(@tabl eData,CHARINDEX ('MyImageData', @tableData) + 12,LEN(@tableDa ta))
PRINT ')' + CHAR(13)
END
ELSE
PRINT @InsertStmt + ' VALUES (' + @tableData + ')' + CHAR(13)


IF @RequiredGo = 1
PRINT 'GO'

END
FETCH NEXT FROM CR_Data INTO @tableData

IF @ImageData <> ''
FETCH NEXT FROM CR_ImageData INTO @ImageData

-- IF @TextData <> ''
-- FETCH NEXT FROM CR_TextData INTO @TextData

END
CLOSE CR_Data
DEALLOCATE CR_Data

IF @ImageData <> ''
BEGIN
CLOSE CR_ImageData
DEALLOCATE CR_ImageData
END


IF @bitIdentity = 1
BEGIN
PRINT 'SET IDENTITY_INSERT [' + @strTableName + '] OFF '
END

PRINT '---- ** End of Inserts ** ----'
RETURN (0)
Mar 29 '08 #1
0 1918

Sign in to post your reply or Sign up for a free account.

Similar topics

3
1482
by: serge calderara | last post by:
Dear all, One simple question relative to store procedure withinh ASP code on a web page. Let say that I am calling a store procedure to execute from a server button click on my web page. That store procedure is returning a bunch of values to my end user. In a matter of time based, what happen from my client web page if my store procedure runs for 3 minutes before returning any data back.
1
2353
by: TARUN | last post by:
Hello All I get stuck in one problem , Please help me and excuse me on the poor Knowledge in SQL Server Store procedure Q1...I want to return a string type value from store procedure , Is it possible to do it.if posible then Please guide us how we can do it .
6
2718
by: c676228 | last post by:
Hi everyone, I wrote a store procedure that fetch one row data in the database based on the parameter value I entered. After I created the store procedure, the store procedure code looks like this: ALTER proc getProductCommScale @product As varchar(30), @TISCommRate As Decimal(5,2) OUTPUT, @BrokerCommRate As Decimal(5,2) OUTPUT, @Fee As Decimal(5,2) OUTPUT As if RTRIM(@product)='Imed' Select @TISCommRate=TISComm,...
0
1856
by: rxding | last post by:
Hello, Performance reason we need to move some of our code into database. Java Store Procedure is given the first choice. However, while investigating some sample code of Java store procedure, PreparedStatement seems to be a must, such as PreparedStatement pstmt = conn.prepareStatement(sql); ..., pstmt.close() in the end. My question is that if the prepareStatement(sql) is called each time when the Java Store Procedure is called, will...
11
4370
by: c676228 | last post by:
Hi everyone, I am just wodering in asp program, if there is anybody writing store procedure for inserting data into database since there are so many parameters need to be passed into store procedure(assume there are many columns in the table). I need to insert data into two separate tables, the relation between these two tables is 1 row of data in table1 could have multiple rows in table2 related to table1, but if the data insertion into...
2
1715
by: Mukesh | last post by:
Hi all I m Using SQL SERVER 2005 I have a requirement to store some data in xmldatatype using stored procedure , Here is example
4
3740
by: JohnnyDeep | last post by:
I am trying to create a store proc that contain a create index with the cluster option and I receive DB21034E The command was processed as an SQL statement because it was not a valid Command Line Processor command. During SQL processing it returned: SQL0623N A clustering index already exists on table "PGIR.TF_RRCE". LINE NUMBER=35. SQLSTATE=55012
4
12427
by: etuncer | last post by:
Hello All, I have Access 2003, and am trying to build a database for my small company. I want to be able to create a word document based on the data entered through a form. the real question is this: can Access create the document and place it as an OLE object to the relevant table? Any help is greatly appreciated. Ricky
1
2456
by: Dave | last post by:
I have multiple forms that will create an object. Basically a energy efficiency measure object. The measure object will have a couple of required properties set but after that it can have 10-20 different fields that are optional per measure. How do I account for the different fields that will be posted from the different forms when I create the measure object? Should I create a constructor method with just the required fields as the...
0
8379
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8709
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8494
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8596
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7309
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4297
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1924
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.