Título do artigo: Liberdade para importar seus dados incrementais - com base nas condições SQLServer volume de tabela gerada pelo processo de melhorias instrução de inserção armazenados
Palavras-chave: mssql-scripter, SQL Server
Artigos Categoria: Tecnologia Compartilhar
Criado em: 05 de abril de 2020
_.-"\
_.-" \
,-" \
\ \
\ \Zoomla逐浪CMS\
\ \ web开发秘笈\ \
\ \ z01.com _.-;
\ \ _.-" :
\ \,-" _.-"
\( _.-"
`--"
- O rápido desenvolvimento da sensibilidade nascido
- Criação de um processo de armazenamento inteligente.
- apresentação recurso
- uso
- Integrado nas CMS ondas
- Suporte SQL2000
- Outro exemplo de Azeri partilha grupo
O rápido desenvolvimento da sensibilidade nascido
desenvolvimento de software, muitas vezes geram dados, backup e restauração de migração de dados, é um tema muito importante.
Para os pequenos desenvolvedores, muitas vezes com a cobertura completa biblioteca.
Para milhões, milhões e banco de dados ainda maior, esta operação é claramente usado por um longo tempo, e vai afetar os principais usos de cenário.
Desta vez, vamos precisar de uma lista de todos os dados ou consulta de acordo com levar para fora, mover para outro da mesma estrutura de biblioteca
Atualmente não há ferramentas para gerar instruções INSERT com base na consulta SQL Server relacionados com, a ferramenta de gerenciamento sqlserver padrão pode gerar um declarações completas de inserção, somente através de ferramentas de terceiros (ferramentas de terceiros) para alcançar.
Na verdade, podemos escrever um script procedimento armazenado para alcançá-lo.
Criação de um processo de armazenamento inteligente.
Este script também muitos online, mas o script on-line ou a falta de algumas das especificações e características, por exemplo: Eu só quero consulta de dados de exportação específica, os scripts on-line está a exportar os dados da tabela inteiras
Se a tabela for grande, terá um impacto significativo no desempenho.
A sintaxe completa para a criação de procedimentos armazenados (por mais de 2005 versões de servidor SQL):
-- Author: <Zoomla!逐浪CMS高端门户团队>
-- Blog: <http://www.z01.com/blog>
-- Create date: <2020/04/05>
-- Description: <根据查询条件导出表数据的insert脚本>
-- =============================================
CREATE PROCEDURE [dbo].[ZL_InsertGenerator]
(
@tableName NVARCHAR(MAX),
@whereClause NVARCHAR(MAX)
)
AS
--Then it includes a cursor to fetch column specific information (column name and the data type thereof)
--from information_schema.columns pseudo entity and loop through for building the INSERT and VALUES clauses
--of an INSERT DML statement.
DECLARE @string NVARCHAR(MAX) --for storing the first half of INSERT statement
DECLARE @stringData NVARCHAR(MAX) --for storing the data (VALUES) related statement
DECLARE @dataType NVARCHAR(MAX) --data types returned for respective columns
DECLARE @schemaName NVARCHAR(MAX) --schema name returned from sys.schemas
DECLARE @schemaNameCount int--shema count
DECLARE @QueryString NVARCHAR(MAX) -- provide for the whole query,
set @QueryString=' '
--如果有多个schema,选择其中一个schema
SELECT @schemaNameCount=COUNT(*)
FROM sys.tables t
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE t.name = @tableName
WHILE(@schemaNameCount>0)
BEGIN
--如果有多个schema,依次指定
select @schemaName = name
from
(
SELECT ROW_NUMBER() over(order by s.schema_id) RowID,s.name
FROM sys.tables t
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE t.name = @tableName
) as v
where RowID=@schemaNameCount
--Declare a cursor to retrieve column specific information
--for the specified table
DECLARE cursCol CURSOR FAST_FORWARD
FOR
SELECT column_name ,
data_type
FROM information_schema.columns
WHERE table_name = @tableName
AND table_schema = @schemaName
OPEN cursCol
SET @string = 'INSERT INTO [' + @schemaName + '].[' + @tableName + ']('
SET @stringData = ''
DECLARE @colName NVARCHAR(500)
FETCH NEXT FROM cursCol INTO @colName, @dataType
PRINT @schemaName
PRINT @colName
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
IF @dataType IN ( 'text', 'ntext' ) --if the datatype
--is text or something else
BEGIN
SET @stringData = @stringData + '''''''''+
isnull(cast(' + @colName + ' as nvarchar(max)),'''')+'''''',''+'
END
ELSE
IF @dataType = 'money' --because money doesn't get converted
--from varchar implicitly
BEGIN
SET @stringData = @stringData
+ '''convert(money,''''''+
isnull(cast(' + @colName
+ ' as nvarchar(max)),''0.0000'')+''''''),''+'
END
ELSE
IF @dataType = 'datetime'
BEGIN
SET @stringData = @stringData
+ '''convert(datetime,''''''+
isnull(cast(' + @colName + ' as nvarchar(max)),''0'')+''''''),''+'
END
ELSE
IF @dataType = 'image'
BEGIN
SET @stringData = @stringData + '''''''''+
isnull(cast(convert(varbinary,' + @colName + ')
as varchar(6)),''0'')+'''''',''+'
END
ELSE --presuming the data type is int,bit,numeric,decimal
BEGIN
SET @stringData = @stringData + '''''''''+
isnull(cast(' + @colName + ' as nvarchar(max)),''0'')+'''''',''+'
END
SET @string = @string + '[' + @colName + ']' + ','
FETCH NEXT FROM cursCol INTO @colName, @dataType
END
--After both of the clauses are built, the VALUES clause contains a trailing comma which needs to be replaced with a single quote. The prefixed clause will only face removal of the trailing comma.
DECLARE @Query NVARCHAR(MAX) -- provide for the whole query,
-- you may increase the size
PRINT @whereClause
IF ( @whereClause IS NOT NULL
AND @whereClause <> ''
)
BEGIN
SET @query = 'SELECT ''' + SUBSTRING(@string, 0, LEN(@string))
+ ') VALUES(''+ ' + SUBSTRING(@stringData, 0,
LEN(@stringData) - 2)
+ '''+'')''
FROM ' +@schemaName+'.'+ @tableName + ' WHERE ' + @whereClause
PRINT @query
-- EXEC sp_executesql @query --load and run the built query
--Eventually, close and de-allocate the cursor created for columns information.
END
ELSE
BEGIN
SET @query = 'SELECT ''' + SUBSTRING(@string, 0, LEN(@string))
+ ') VALUES(''+ ' + SUBSTRING(@stringData, 0,
LEN(@stringData) - 2)
+ '''+'')''
FROM ' + @schemaName+'.'+ @tableName
END
CLOSE cursCol
DEALLOCATE cursCol
SET @schemaNameCount=@schemaNameCount-1
IF(@schemaNameCount=0)
BEGIN
SET @QueryString=@QueryString+@query
END
ELSE
BEGIN
SET @QueryString=@QueryString+@query+' UNION ALL '
END
PRINT convert(varchar(max),@schemaNameCount)+'---'+@QueryString
END
EXEC sp_executesql @QueryString --load and run the built query
--Eventually, close and de-allocate the cursor created for columns information.
apresentação recurso
Aqui a declarar que, se você tem vários esquemas, e cada um tem o mesmo esquema da tabela abaixo, o script irá gerar um esquema no qual a tabela insira o seguinte script
Por exemplo, agora tenho três esquema, o seguinte tem a tabela de clientes
CREATE TABLE dbo.[customer](city int,region int)
CREATE SCHEMA test
CREATE TABLE test.[customer](city int,region int)
CREATE SCHEMA test1
CREATE TABLE test1.[customer](city int,region int)
Ao executar o script ele só iria gerar a tabela de esquema dbo insira o seguinte script
INSERT INTO [dbo].[customer]([city],[region]) VALUES('1','2')
Este script tem uma falha
Se o seu campo é o tipo de tabelas de dados, o guia saiu único personagem
Estrutura tabela
CREATE TABLE [dbo].[customer](city int,region int)
Guiada pelo script de inserção:
INSERT INTO [dbo].[customer]([city],[region]) VALUES('1','2')
uso
Há duas maneiras
1, os dados da tabela de guia inteiro
ZL_InsertGenerator 'customer', null
ou:
ZL_InsertGenerator 'customer', ' '
2. A consulta de dados piloto
ZL_InsertGenerator 'customer', 'city=3'
ou
ZL_InsertGenerator 'customer', 'city=3 and region=8'
Clique em, selecione Todos
Em seguida, copie
Criar uma nova janela de consulta, e em seguida, cole
Integrado nas CMS ondas
Na verdade, SQLServer tem um monte de habilidades, tais como a utilização de uma combinação de variáveis, atualizações dinâmicas, como o script a seguir:
set @最近查询时间 = '2020-04-5 19:35:57.000'
set @主表最近GID=(
select top 1 GeneralID from ZL_CommonModel left join ZL_C_image on ZL_CommonModel.ItemID=ZL_C_image.id where
UpDateTime<@最近查询时间 and ModelID=52 and Status=99 order by UpDateTime desc )
set @副表最近ID=(
select top 1 ID from ZL_CommonModel left join ZL_C_image on ZL_CommonModel.ItemID=ZL_C_image.id where
UpDateTime<@最近查询时间 and ModelID=52 and Status=99 order by UpDateTime desc)
select @最近查询时间 as 最近查询时间,@主表最近GID as 主表最近GID,@副表最近ID as 副表最近ID
Passo Dois: Os seguintes dois números de identificação acima dos dois transdutores, um único sintaxe de consulta obtido, e com:
SET IDENTITY_INSERT [Table] ON
SET IDENTITY_INSERT [Table] OFF
使用
ZL_InsertGenerator 'ZL_CommonModel','GeneralID>=9351'
go
ZL_InsertGenerator 'zl_c_image','id>=9352'
Suporte SQL2000
Finalmente, podemos olhar para o código, muito simples, se você quiser apoiar SQLServer2000, basta alterar o código sobre ele (embora não muito sql2000 usuários, mas você pode aprender o roteiro apropriado).
Adicionado: criar uma tabela de teste
CREATE TABLE testinsert (id INT,name VARCHAR(100),cash MONEY,dtime DATETIME)
INSERT INTO [dbo].[testinsert]
( [id], [name], [cash], [dtime] )
VALUES ( 1, -- id - int
'nihao', -- name - varchar(100)
8.8, -- cash - money
GETDATE() -- dtime - datetime
)
SELECT * FROM [dbo].[testinsert]
teste
InsertGenerator 'testinsert' ,''
InsertGenerator 'testinsert' ,'name=''nihao'''
InsertGenerator 'testinsert' ,'name=''nihao'' and cash=8.8'
datetime haverá algum tipo de problema
Os resultados são gerados automaticamente para ajudá-lo converter
INSERT INTO [dbo].[testinsert]([id],[name],[cash],[dtime]) VALUES('1','nihao',convert(money,'8.80'),convert(datetime,'02 8 2015 5:17PM'))
Outro exemplo de Azeri partilha grupo
IF OBJECT_ID('spGenInsertSQL','P') IS NOT NULL
DROP PROC spGenInsertSQL
GO
CREATE proc spGenInsertSQL (@tablename varchar(256),@number BIGINT,@whereClause NVARCHAR(MAX))
as
begin
declare @sql varchar(8000)
declare @sqlValues varchar(8000)
set @sql =' ('
set @sqlValues = 'values (''+'
select @sqlValues = @sqlValues + cols + ' + '','' + ' ,@sql = @sql + '[' + name + '],'
from
(select case
when xtype in (48,52,56,59,60,62,104,106,108,122,127)
then 'case when '+ name +' is null then ''NULL'' else ' + 'cast('+ name + ' as varchar)'+' end'
when xtype in (58,61,40,41,42)
then 'case when '+ name +' is null then ''NULL'' else '+''''''''' + ' + 'cast('+ name +' as varchar)'+ '+'''''''''+' end'
when xtype in (167)
then 'case when '+ name +' is null then ''NULL'' else '+''''''''' + ' + 'replace('+ name+','''''''','''''''''''')' + '+'''''''''+' end'
when xtype in (231)
then 'case when '+ name +' is null then ''NULL'' else '+'''N'''''' + ' + 'replace('+ name+','''''''','''''''''''')' + '+'''''''''+' end'
when xtype in (175)
then 'case when '+ name +' is null then ''NULL'' else '+''''''''' + ' + 'cast(replace('+ name+','''''''','''''''''''') as Char(' + cast(length as varchar) + '))+'''''''''+' end'
when xtype in (239)
then 'case when '+ name +' is null then ''NULL'' else '+'''N'''''' + ' + 'cast(replace('+ name+','''''''','''''''''''') as Char(' + cast(length as varchar) + '))+'''''''''+' end'
else '''NULL'''
end as Cols,name
from syscolumns
where id = object_id(@tablename)
) T
IF (@number!=0 AND @number IS NOT NULL)
BEGIN
set @sql ='select top '+ CAST(@number AS VARCHAR(6000))+' ''INSERT INTO ['+ @tablename + ']' + left(@sql,len(@sql)-1)+') ' + left(@sqlValues,len(@sqlValues)-4) + ')'' from '+@tablename
print @sql
END
ELSE
BEGIN
set @sql ='select ''INSERT INTO ['+ @tablename + ']' + left(@sql,len(@sql)-1)+') ' + left(@sqlValues,len(@sqlValues)-4) + ')'' from '+@tablename
print @sql
END
PRINT @whereClause
IF ( @whereClause IS NOT NULL AND @whereClause <> '')
BEGIN
set @sql =@sql+' where '+@whereClause
print @sql
END
exec (@sql)
end
GO
chamadas de exemplo
--非dbo默认架构需注意
--支持数据类型 :bigint,int, bit,char,datetime,date,time,decimal,money, nvarchar(50),tinyint, nvarchar(max),varchar(max),datetime2
--调用示例 如果top行或者where条件为空,只需要把参数填上null
spGenInsertSQL 'customer' --表名
, 2 --top 行数
, 'city=3 and didian=''大连'' ' --where 条件
--导出全表 where条件为空
spGenInsertSQL 'customer' --表名
, null --top 行数
,null --where 条件
INSERT INTO [Department] ([DepartmentID],[Name],[GroupName],[Company],[ModifiedDate]) values (1,N'售后部',N'销售组',N'中国你好有限公司XX分公司','05 5 2015 5:58PM')
INSERT INTO [Department] ([DepartmentID],[Name],[GroupName],[Company],[ModifiedDate]) values (2,N'售后部',N'销售组',N'中国你好有限公司XX分公司','05 5 2015 5:58PM')