CREATE PROCEDURE [dbo].[usp_InsertGenerator]
AS
BEGIN
DECLARE @tablename varchar(100)
CREATE TABLE #TempTable
(
Name varchar(max)
)
INSERT INTO #TempTable (Name)
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
SET @tablename = (SELECT name FROM #TempTable)
DECLARE cursCol CURSOR FAST_FORWARD FOR
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = @tableName
OPEN cursCol
DECLARE @string nvarchar(3000)
DECLARE @stringData nvarchar(3000)
DECLARE @dataType nvarchar(1000)
SET @string='INSERT '+@tableName+'('
SET @stringData=''
DECLARE @colName nvarchar(50)
FETCH NEXT FROM cursCol INTO @colName, @dataType
IF @@fetch_status <> 0
BEGIN
PRINT 'Table '+@tableName+' not found, processing skipped.'
CLOSE curscol
DEALLOCATE curscol
RETURN
END
WHILE @@FETCH_STATUS = 0
BEGIN
IF @dataType IN ('varchar','char','nchar','nvarchar')
BEGIN
SET @stringData=@stringData+'''''''''+
isnull('+@colName+','''')+'''''',''+'
END
ELSE
BEGIN
SET @stringData=@stringData+'''''''''+
isnull(cast('+@colName+' as varchar(200)),''0'')+'''''',''+'
END
SET @string=@string+@colName+','
FETCH NEXT FROM cursCol INTO @colName ,@dataType
END
begin
DECLARE @Query nvarchar(4000)
SET @query ='SELECT '''+substring(@string,0,len(@string)) + ')
VALUES(''+ ' + substring(@stringData,0,len(@stringData)-2)+'''+'')''
FROM '+@tableName
exec (@query)
CLOSE cursCol
DEALLOCATE cursCol
end
end
go
Trying to generate script with data for all the tables in on go. I need to set @tablename for all the tables which are present in database.
DECLARE @tablename varchar(100)
CREATE TABLE #TempTable(
Name varchar(max))
INSERT INTO #TempTable ( Name)
SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_TYPE= 'BASE TABLE'
set @tablename=(SELECT name from #TempTable )
When executing the above procedure , it given the below error. how can I set multiple values for any variable after declaring the same .
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=,
<, <= , >, >= or when the subquery is used as an expression.