1
我想從一個表(或存儲過程)插入數據到臨時表。臨時表列計數與源表列計數不匹配。我想要將來源數據從開始列插入到臨時表中,其餘列將清空字符串列。從另一個表中插入表甚至列數不匹配?
這意味着如果Temp
表有10列,並且源表只有3列,則將前3列插入臨時表中,其餘7列將爲空或空。
例子:
CREATE TABLE #VarTemp(Col1 nvarchar(256), Col2 nvarchar(256), Col3 nvarchar(256),
Col4 nvarchar(256), Col5 nvarchar(256), Col6 nvarchar(256),
Col7 nvarchar(256), Col8 nvarchar(256), Col9 nvarchar(256),
Col10 nvarchar(256))
INSERT into #VarTemp
EXEC sp_FindStringInTable 'Nareshbhai%', 'dbo', 'UserstoClean';
SELECT * FROM #VarTemp
如果我執行單獨
EXEC sp_FindStringInTable 'Nareshbhai%', 'dbo', 'UserstoClean';
我越來越
Constitid FirstName LastName email status pincode
3151502 Nareshbhai Desai [email protected] Inactive desai
錯誤是
有一個錯誤。檢查以確保對象存在。 (0行(S)的影響)
消息0,級別11,狀態0,行0
當前命令發生了嚴重錯誤。如果有的話,結果應該被丟棄。
sp_FindStringInTable
是
ALTER PROCEDURE [dbo].[sp_FindStringInTable]
@stringToFind VARCHAR(100), @schema sysname, @table sysname
AS
DECLARE @sqlCommand VARCHAR(8000)
DECLARE @where VARCHAR(8000)
DECLARE @columnName sysname
DECLARE @cursor VARCHAR(8000)
BEGIN TRY
SET @sqlCommand = 'SELECT * FROM ' + @schema + '.' + @table + ' WHERE'
SET @where = ''
SET @cursor = 'DECLARE col_cursor CURSOR FOR
SELECT COLUMN_NAME
FROM ' + DB_NAME() + '.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = ''' + @schema + '''
AND TABLE_NAME = ''' + @table + '''
AND DATA_TYPE IN (''char'', ''nchar'', ''ntext'', ''nvarchar'', ''text'', ''varchar'')'
EXEC (@cursor)
OPEN col_cursor
FETCH NEXT FROM col_cursor INTO @columnName
WHILE @@FETCH_STATUS = 0
BEGIN
IF @where <> ''
SET @where = @where + ' OR'
SET @where = @where + ' ' + @columnName + ' LIKE ''' + @stringToFind + ''''
FETCH NEXT FROM col_cursor INTO @columnName
END
CLOSE col_cursor
DEALLOCATE col_cursor
SET @sqlCommand = @sqlCommand + @where
--PRINT @sqlCommand
EXEC (@sqlCommand)
END TRY
BEGIN CATCH
PRINT 'There was an error. Check to make sure object exists.'
IF CURSOR_STATUS('variable', 'col_cursor') <> -3
BEGIN
CLOSE col_cursor
DEALLOCATE col_cursor
END
END CATCH
GO