데이터 베이스 MySQL 튜토리얼 收藏几段SQL Server语句和存储过程

收藏几段SQL Server语句和存储过程

Jun 07, 2016 pm 03:04 PM
server sql 여러 개의 저장 모으다 성명 프로세스

收藏 几段SQL Server 语句 和 存储 过程 (标准化越来越近了) :namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /> -- ====================================================== --列出sql server (WINDOWS平台上强大的数据库平台) 所

收藏几段SQL  Server语句存储过程(标准化越来越近了):namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

 

-- ======================================================

--列出sql server(WINDOWS平台上强大的数据库平台) 所有表,字段名,主键,类型,长度,小数位数等信息

--在查询分析器里运行即可,可以生成一个表,导出到EXCEL中

-- ======================================================

SELECT

    (case when a.colorder=1 then d.name else '' end)表名,

    a.colorder 字段序号,

    a.name 字段名,

    (case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '√'else '' end) 标识,

    (case when (SELECT count(*)

    FROM sysobjects

    WHERE (name in

          (SELECT name

         FROM sysindexes

          WHERE (id = a.id) AND (indid in

               (SELECT indid

              FROM sysindexkeys

              WHERE (id = a.id) AND (colid in

                   (SELECT colid

                   FROM syscolumns

                  WHERE (id = a.id) AND (name = a.name))))))) AND

        (xtype = 'PK'))>0 then '√' else '' end) 主键,

    b.name 类型,

    a.length 占用字节数,

    COLUMNPROPERTY(a.id,a.name,'PRECISION') as 长度,

    isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) as 小数位数,

    (case when a.isnullable=1 then '√'else '' end) 允许空,

    isnull(e.text,'') 默认值,

    isnull(g.[value],'') AS 字段说明  

 

FROM  syscolumns  a left join systypes b

on  a.xtype=b.xusertype

inner join sysobjects d

on a.id=d.id  and  d.xtype='U' and  d.name'dtproperties'

left join syscomments e

on a.cdefault=e.id

left join sysproperties g

on a.id=g.id AND a.colid = g.smallid 

order by a.id,a.colorder

-------------------------------------------------------------------------------------------------

 

 

 

 

 

 

列出sql server(WINDOWS平台上强大的数据库平台) 所有表、字段定义,类型,长度,一个值等信息

并导出到Excel 中

-- ======================================================

-- Export all user tables definition and one sample value

-- jan-13-2003,Dr.Zhang

-- ======================================================

在查询分析器里运行:

SET ANSI_NULLS OFF

GO

SET NOCOUNT ON

GO

 

SET LANGUAGE 'Simplified Chinese'

go

DECLARE @tbl nvarchar(200),@fld nvarchar(200),@sql nvarchar(4000),@maxlen int,@sample nvarchar(40)

 

SELECT d.name TableName,a.name FieldName,b.name TypeName,a.length Length,a.isnullable IS_NULL INTO #t

FROM  syscolumns  a,  systypes b,sysobjects d 

WHERE  a.xtype=b.xusertype  and  a.id=d.id  and  d.xtype='U'

 

DECLARE read_cursor CURSOR

FOR SELECT TableName,FieldName FROM #t

 

SELECT TOP 1 '_TableName           ' TableName,

       'FieldName            ' FieldName,'TypeName       ' TypeName,

       'Length' Length,'IS_NULL' IS_NULL,

       'MaxLenUsed' AS MaxLenUsed,'Sample Value      ' Sample,

       'Comment  ' Comment INTO #tc FROM #t

 

OPEN read_cursor

 

FETCH NEXT FROM read_cursor INTO @tbl,@fld

WHILE (@@fetch_status -1)  --- failes

BEGIN

    IF (@@fetch_status -2) -- Missing

    BEGIN

        SET @sql=N'SET @maxlen=(SELECT max(len(cast('+@fld+' as nvarchar))) FROM '+@tbl+')'

        --PRINT @sql

        EXEC SP_EXECUTESQL @sql,N'@maxlen int OUTPUT',@maxlen OUTPUT

        --print @maxlen

        SET @sql=N'SET @sample=(SELECT TOP 1 cast('+@fld+' as nvarchar) FROM '+@tbl+' WHERE len(cast('+@fld+' as nvarchar))='+convert(nvarchar(5),@maxlen)+')'

        EXEC SP_EXECUTESQL @sql,N'@sample varchar(30) OUTPUT',@sample OUTPUT

        --for quickly 

        --SET @sql=N'SET @sample=convert(varchar(20),(SELECT TOP 1 '+@fld+' FROM '+

           --@tbl+' order by 1 desc ))' 

        PRINT @sql

        print @sample

        print @tbl

        EXEC SP_EXECUTESQL @sql,N'@sample nvarchar(30) OUTPUT',@sample OUTPUT

        INSERT INTO #tc SELECT *,ltrim(ISNULL(@maxlen,0)) as MaxLenUsed,

           convert(nchar(20),ltrim(ISNULL(@sample,' '))) as Sample,' ' Comment FROM #t where TableName=@tbl and FieldName=@fld

    END

    FETCH NEXT FROM read_cursor INTO @tbl,@fld

END

 

CLOSE read_cursor

DEALLOCATE read_cursor

GO

 

SET ANSI_NULLS ON

GO

SET NOCOUNT OFF

GO

select count(*)  from #t

DROP TABLE #t

GO

 

select count(*)-1  from #tc

 

select * into ##tx from #tc order by tablename

DROP TABLE #tc

 

--select * from ##tx

 

declare @db nvarchar(60),@sql nvarchar(3000)

set @db=db_name()

--请修改用户名和口令 导出到Excel 中

set @sql='exec master.dbo.xp_cmdshell ''bcp ..dbo.##tx out c:\'+@db+'_exp.xls -w -C936 -(标准化越来越近了):namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" />Usa -Psa '''

print @sql

exec(@sql)

GO

DROP TABLE ##tx

GO

 

 

 

-- ======================================================

--根据表中数据生成insert语句存储过程

--建立存储过程,执行 spGenInsertSQL 表名

--感谢playyuer

-- ======================================================

CREATE  proc spGenInsertSQL (@tablename varchar(256))

 

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)

            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

  set @sql ='select ''INSERT INTO ['+ @tablename + ']' + left(@sql,len(@sql)-1)+') ' + left(@sqlValues,len(@sqlValues)-4) + ')'' from '+@tablename

  --print @sql

  exec (@sql)

end

 

GO

 

 

 

-- ======================================================

--根据表中数据生成insert语句存储过程

--建立存储过程,执行 proc_insert 表名

--感谢Sky_blue

-- ======================================================

 

CREATE proc proc_insert (@tablename varchar(256))

as

begin

    set nocount on

    declare @sqlstr varchar(4000)

    declare @sqlstr1 varchar(4000)

    declare @sqlstr2 varchar(4000)

    select @sqlstr='select ''insert '+@tablename

    select @sqlstr1=''

    select @sqlstr2=' ('

    select @sqlstr1= ' values ( ''+'

    select @sqlstr1=@sqlstr1+col+'+'',''+' ,@sqlstr2=@sqlstr2+name +',' from (select case

--   when a.xtype =173 then 'case when '+a.name+' is null then ''NULL'' else '+'convert(varchar('+convert(varchar(4),a.length*2+2)+'),'+a.name +')'+' end'

    when a.xtype =104 then 'case when '+a.name+' is null then ''NULL'' else '+'convert(varchar(1),'+a.name +')'+' end'

    when a.xtype =175 then 'case when '+a.name+' is null then ''NULL'' else '+'''''''''+'+'replace('+a.name+','''''''','''''''''''')' + '+'''''''''+' end'

    when a.xtype =61  then 'case when '+a.name+' is null then ''NULL'' else '+'''''''''+'+'convert(varchar(23),'+a.name +',121)'+ '+'''''''''+' end'

    when a.xtype =106 then 'case when '+a.name+' is null then ''NULL'' else '+'convert(varchar('+convert(varchar(4),a.xprec+2)+'),'+a.name +')'+' end'

    when a.xtype =62  then 'case when '+a.name+' is null then ''NULL'' else '+'convert(varchar(23),'+a.name +',2)'+' end'

    when a.xtype =56  then 'case when '+a.name+' is null then ''NULL'' else '+'convert(varchar(11),'+a.name +')'+' end'

    when a.xtype =60  then 'case when '+a.name+' is null then ''NULL'' else '+'convert(varchar(22),'+a.name +')'+' end'

    when a.xtype =239 then 'case when '+a.name+' is null then ''NULL'' else '+'''''''''+'+'replace('+a.name+','''''''','''''''''''')' + '+'''''''''+' end'

    when a.xtype =108 then 'case when '+a.name+' is null then ''NULL'' else '+'convert(varchar('+convert(varchar(4),a.xprec+2)+'),'+a.name +')'+' end'

    when a.xtype =231 then 'case when '+a.name+' is null then ''NULL'' else '+'''''''''+'+'replace('+a.name+','''''''','''''''''''')' + '+'''''''''+' end'

    when a.xtype =59  then 'case when '+a.name+' is null then ''NULL'' else '+'convert(varchar(23),'+a.name +',2)'+' end'

    when a.xtype =58  then 'case when '+a.name+' is null then ''NULL'' else '+'''''''''+'+'convert(varchar(23),'+a.name +',121)'+ '+'''''''''+' end'

    when a.xtype =52  then 'case when '+a.name+' is null then ''NULL'' else '+'convert(varchar(12),'+a.name +')'+' end'

    when a.xtype =122 then 'case when '+a.name+' is null then ''NULL'' else '+'convert(varchar(22),'+a.name +')'+' end'

    when a.xtype =48  then 'case when '+a.name+' is null then ''NULL'' else '+'convert(varchar(6),'+a.name +')'+' end'

--   when a.xtype =165 then 'case when '+a.name+' is null then ''NULL'' else '+'convert(varchar('+convert(varchar(4),a.length*2+2)+'),'+a.name +')'+' end'

    when a.xtype =167 then 'case when '+a.name+' is null then ''NULL'' else '+'''''''''+'+'replace('+a.name+','''''''','''''''''''')' + '+'''''''''+' end'

    else '''NULL'''

    end as col,a.colid,a.name

    from syscolumns a where a.id = object_id(@tablename) and a.xtype 189 and a.xtype 34 and a.xtype 35 and  a.xtype 36

    )t order by colid

   

    select @sqlstr=@sqlstr+left(@sqlstr2,len(@sqlstr2)-1)+') '+left(@sqlstr1,len(@sqlstr1)-3)+')'' from '+@tablename

--  print @sqlstr

    exec( @sqlstr)

    set nocount off

end

GO

1 2 3 4 5 6  下一页

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Hibernate 프레임워크에서 HQL과 SQL의 차이점은 무엇입니까? Hibernate 프레임워크에서 HQL과 SQL의 차이점은 무엇입니까? Apr 17, 2024 pm 02:57 PM

HQL과 SQL은 Hibernate 프레임워크에서 비교됩니다. HQL(1. 객체 지향 구문, 2. 데이터베이스 독립적 쿼리, 3. 유형 안전성), SQL은 데이터베이스를 직접 운영합니다(1. 데이터베이스 독립적 표준, 2. 복잡한 실행 파일) 쿼리 및 데이터 조작).

Oracle SQL의 나누기 연산 사용법 Oracle SQL의 나누기 연산 사용법 Mar 10, 2024 pm 03:06 PM

"OracleSQL의 나눗셈 연산 사용법" OracleSQL에서 나눗셈 연산은 일반적인 수학 연산 중 하나입니다. 데이터 쿼리 및 처리 중에 나누기 작업은 필드 간의 비율을 계산하거나 특정 값 간의 논리적 관계를 도출하는 데 도움이 될 수 있습니다. 이 문서에서는 OracleSQL의 나누기 작업 사용법을 소개하고 구체적인 코드 예제를 제공합니다. 1. OracleSQL의 두 가지 분할 연산 방식 OracleSQL에서는 두 가지 방식으로 분할 연산을 수행할 수 있습니다.

SQL의 ID 속성은 무엇을 의미합니까? SQL의 ID 속성은 무엇을 의미합니까? Feb 19, 2024 am 11:24 AM

SQL에서 ID란 무엇입니까? SQL에서 ID는 자동 증가 숫자를 생성하는 데 사용되는 특수 데이터 유형으로, 테이블의 각 데이터 행을 고유하게 식별하는 데 사용됩니다. ID 열은 일반적으로 기본 키 열과 함께 사용되어 각 레코드에 고유한 식별자가 있는지 확인합니다. 이 문서에서는 Identity를 사용하는 방법과 몇 가지 실제 코드 예제를 자세히 설명합니다. Identity를 사용하는 기본 방법은 테이블을 생성할 때 Identit을 사용하는 것입니다.

Oracle과 DB2의 SQL 구문 비교 및 ​​차이점 Oracle과 DB2의 SQL 구문 비교 및 ​​차이점 Mar 11, 2024 pm 12:09 PM

Oracle과 DB2는 일반적으로 사용되는 관계형 데이터베이스 관리 시스템으로, 각각 고유한 SQL 구문과 특성을 가지고 있습니다. 이 기사에서는 Oracle과 DB2의 SQL 구문을 비교 및 ​​차이점을 설명하고 구체적인 코드 예제를 제공합니다. 데이터베이스 연결 Oracle에서는 다음 문을 사용하여 데이터베이스에 연결합니다. CONNECTusername/password@database DB2에서 데이터베이스에 연결하는 문은 다음과 같습니다. CONNECTTOdataba

화웨이는 내년에 혁신적인 MED 스토리지 제품을 출시할 예정입니다. 랙 용량은 10PB를 초과하고 전력 소비량은 2kW 미만입니다. 화웨이는 내년에 혁신적인 MED 스토리지 제품을 출시할 예정입니다. 랙 용량은 10PB를 초과하고 전력 소비량은 2kW 미만입니다. Mar 07, 2024 pm 10:43 PM

이 웹사이트는 3월 7일 화웨이의 데이터 스토리지 제품 라인 사장인 Zhou Yuefeng 박사가 최근 MWC2024 컨퍼런스에 참석하여 웜 데이터(WarmData)와 콜드 데이터(ColdData)용으로 설계된 차세대 OceanStorArctic 자전 스토리지 솔루션을 구체적으로 시연했다고 보도했습니다. Huawei의 데이터 스토리지 제품 라인 사장 Zhou Yuefeng은 일련의 혁신적인 솔루션을 출시했습니다. 이미지 출처: 이 사이트에 첨부된 Huawei의 공식 보도 자료는 다음과 같습니다. 이 솔루션의 가격은 자기 테이프보다 20% 저렴하며, 전력 소비는 하드 디스크보다 90% 낮습니다. 해외 기술 매체인 blockandfiles에 따르면, Huawei 대변인은 자기전기 저장 솔루션에 대한 정보도 공개했습니다. Huawei의 자기전자 디스크(MED)는 자기 저장 매체의 주요 혁신입니다. 1세대 ME

MyBatis 동적 SQL 태그의 Set 태그 기능에 대한 자세한 설명 MyBatis 동적 SQL 태그의 Set 태그 기능에 대한 자세한 설명 Feb 26, 2024 pm 07:48 PM

MyBatis 동적 SQL 태그 해석: Set 태그 사용법에 대한 자세한 설명 MyBatis는 풍부한 동적 SQL 태그를 제공하고 데이터베이스 작업 명령문을 유연하게 구성할 수 있는 탁월한 지속성 계층 프레임워크입니다. 그 중 Set 태그는 업데이트 작업에서 매우 일반적으로 사용되는 UPDATE 문에서 SET 절을 생성하는 데 사용됩니다. 이 기사에서는 MyBatis에서 Set 태그의 사용법을 자세히 설명하고 특정 코드 예제를 통해 해당 기능을 보여줍니다. Set 태그란 무엇입니까? Set 태그는 MyBati에서 사용됩니다.

Douyin에 소다 음악 노래를 추가하는 방법 Douyin에 소다 음악 노래를 추가하는 방법 Feb 23, 2024 pm 04:52 PM

Douyin에 소다 음악을 추가하는 방법 소다 음악 앱의 노래는 Douyin 플랫폼과 동기화될 수 있지만 대부분의 친구들은 Douyin에 소다 음악을 추가하는 방법을 모릅니다. 다음은 편집자가 사용자에게 안내할 것입니다. Douyin에 소다 음악 노래를 추가하는 방법에 관심이 있는 사용자는 와서 살펴볼 수 있습니다! 소다 음악 사용에 대한 튜토리얼 Douyin에 소다 음악을 추가하는 방법 1. 먼저 소다 음악 앱을 열고 메인 페이지 하단의 [음악] 아이콘을 클릭하여 페이지로 들어갑니다. , [아래 그림 화살표] 공유] 버튼을 클릭합니다. 3. 마지막으로 아래 확장된 기능 표시줄에서 [Douyin] 아이콘을 선택하여 해당 플랫폼에 공유합니다.

SQL에서 5120 오류를 해결하는 방법 SQL에서 5120 오류를 해결하는 방법 Mar 06, 2024 pm 04:33 PM

해결 방법: 1. 로그인한 사용자에게 데이터베이스에 액세스하거나 운영할 수 있는 충분한 권한이 있는지 확인하고 해당 사용자에게 올바른 권한이 있는지 확인하십시오. 2. SQL Server 서비스 계정에 지정된 파일에 액세스할 수 있는 권한이 있는지 확인하십시오. 3. 지정된 데이터베이스 파일이 다른 프로세스에 의해 열렸거나 잠겼는지 확인하고 파일을 닫거나 해제한 후 쿼리를 다시 실행하십시오. .관리자로 Management Studio를 실행해 보세요.

See all articles