블로그 이미지
010-9967-0955 보미아빠

카테고리

보미아빠, 석이 (500)
밥벌이 (16)
싸이클 (1)
일상 (1)
Total
Today
Yesterday

달력

« » 2015.11
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30

공지사항

최근에 올라온 글

'2015/11'에 해당되는 글 7건

  1. 2015.11.30 threadpool 을 이용한 처리 (64개이상 처리를 위해 수정됨)
  2. 2015.11.27 dbcc writepage
  3. 2015.11.27 DBCC CHECKPRIMARYFILE
  4. 2015.11.26 index only script
  5. 2015.11.21 string.format
  6. 2015.11.11 vs 테마바꾸기
  7. 2015.11.04 단위변환

// program.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadPoolTest
{
    class Program
    {
        static void Main(string[] args)
        {
            PoolWorker poolWorker = new PoolWorker();
            poolWorker.DoWork();
        }
    }
}











// poolworker.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadPoolTest
{
    // 메인워커가 일 끝내고 나서 처리할 함수를 위한 deletegate
    public delegate void ThreadCallBackMethod(string parameter1);

    class PoolWorker
    {
        public void DoWork()
        {
            int setMinTrheads = 1;
            int setMaxThreads = 6;
            int doWorkCnt = 100;

            ThreadPool.SetMinThreads(setMinTrheads, setMinTrheads);
            ThreadPool.SetMaxThreads(setMaxThreads, setMaxThreads);

            List<ManualResetEvent> manualResetEvents = new List<ManualResetEvent>();
           
            for (int i = 0; i < doWorkCnt; i++)
            {
                ThreadPoolStatus threadPoolStatus = new ThreadPoolStatus();
                threadPoolStatus.signal = new ManualResetEvent(false);
                manualResetEvents.Add(threadPoolStatus.signal);

                MainWorker mainWorker = new MainWorker(i, ThreadCompletedAndExecuteMethod);
                ThreadPool.QueueUserWorkItem(mainWorker.DoWork, threadPoolStatus);
            }
            WaitForAll(manualResetEvents);
        }

        //각각의 메인워커들이 실행을 끝내고 수행할 함수
        public static void ThreadCompletedAndExecuteMethod(string msg)
        {
            Console.WriteLine("ThreadCallback Excuted..{0}", msg);
        }

       
        static void WaitForAll(List<ManualResetEvent> manualResetEvents)
        {
            if (manualResetEvents == null) return;
            foreach (ManualResetEvent t in manualResetEvents)
            {
                // 신호 받을때까지 메인을 차단하는 역할
                t.WaitOne();
            }
        }
    }


    public class ThreadPoolStatus
    {
        public ManualResetEvent signal;
    }
}












// mainworker.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadPoolTest
{
    class MainWorker
    {
        int parameter;
        ThreadCallBackMethod callbackMethodName;

        public MainWorker(int parameter, ThreadCallBackMethod methodName)
        {
            this.parameter = parameter;
            this.callbackMethodName = methodName;
        }

        public void DoWork(object theadPoolStatus)
        {
            ThreadPoolStatus status = theadPoolStatus as ThreadPoolStatus;
            if (status == null) return;

            Thread.Sleep(500);
            Console.WriteLine(parameter);
            callbackMethodName(this.parameter.ToString());

            status.signal.Set();
        }
    }
}


Posted by 보미아빠
, |

dbcc writepage

카테고리 없음 / 2015. 11. 27. 18:40

아래 명령어를 써 문제가 되면 아무도 책임져 주지 않습니다.

목숨 걸어야 할때만 쓰세요 (백업도 없고.....-_- 아무도 안도와줘~ )


823 윈도우 api 로 읽기 쓰기할때 장치가 없거나 억세스 할 수 없을때 로깅
824 checksum 값이 실제값과 예상값이 틀림


오류: 824, 심각도: 24, 상태: 2.

SQL Server detected a logical consistency-based I/O error: 체크섬이 잘못되었습니다(예상: 0xfc3881de, 실제: 0xa0e6ae8a).. It occurred during a 읽기 of page (4:133015609) in database ID 6 at offset 0x0000fdb5072000 in file 'O:\db.ndf'.  Additional messages in the SQL Server error log or system event log may provide more detail. This is a severe error condition that threatens database integrity and must be corrected immediately. Complete a full database consistency check (DBCC CHECKDB). This error can be caused by many factors; for more information, see SQL Server Books Online. 



1개 페이지의 내용의 잘못된 값은 포기하고, 실제 계산된 체크섬값을 기록해 보기로 한다면,
dbcc traceon (3604, -1)
dbcc WRITEPAGE ('db', 4, 133015609, 60, 4, 0x8aaee6a0, 1) 명령어를 이용해 수정을 시도 합니다.
인자는 (데이터베이스 이름, 파일번호, 체크섬값의 offset 위치 항상 같음, 몇바이트를 라이트할지, 입력할 값, 디스크에 바로기록)

위 로그에서 offset 값은  0x0000fdb5072000  에서 8192로 나누면 page번호값이 나옵니다. 왜 두번 나오게 했나 몰라 -_-~
0x0000fdb5072000 / 8192 = 133015609


클러스터 시스템에서 운영되는 SQL Server 는 OS 에서 SQL 서버 먼저 내리고 끌것!
원래 shutdown 을 클릭하면 리소스를 넘기고 꺼지지만, 어떤 오류가 있어 리소스를 정상적으로 offline 못 시키고 다운 될 경우도 있고 이 경우 디스크가 먼저 떨어져 sql 에서 파일을 핸들링 하려고 하는데, 디스크가 없어져버리는 823을 일으킬 가능성이 있고, 또 이것이 데이터만 쓰고 체크섬은 기록하지 못하는 824 오류를 만들어 낼 수 있다.

더 심각한 것은 데이터베이스 복구는 roll-forward roll-back 이라는 잘 알려진 프로세스에 의해 복구가 된다. 최근 페이지에 checkpoint 후 발생한 어떤 트랜젝션에서 commit 이 있었다면 roll-forward 를 이용해 다시 써야 한다. 그런데, 해당 페이지에 824 checksum 미스매치가 발생했다면 복구 프로세스를 완료하지 못하게 된다. 사실 이 페이지가 checksum 오류가 일어나기 쉬운 포인트 이기도 하다. 디스크에 써 지다가 디스크가 떨어져 버렸으니 말이다.

엔터프라이즈의 경우 deffered transaction 이나 자동 페이지복구 기능으로 복구가 가능할 수 있다.

Transaction rollforard 에서 걸리는 경우 복구 가능한지는 테스트가 필요하다.

 

https://msdn.microsoft.com/en-us/library/ms188290.aspx
https://msdn.microsoft.com/ko-kr/library/bb677167(v=sql.120).aspx
http://www.sqlskills.com/blogs/paul/disaster-recovery-101-dealing-with-negative-spids-2-and-3/


실제

오류: 824, 심각도: 24, 상태: 2.

오류: 3313, 심각도: 21, 상태: 2.

SQL Server detected a logical consistency-based I/O error: 체크섬이 잘못되었습니다(예상: 0xfc3881de, 실제: 0xa0e6ae8a).. It occurred during a 읽기 of page (4:133015609) in database ID 6 at offset 0x0000fdb5072000 in file 'O:\xx.ndf'.  Additional messages in the SQL Server error log or system event log may provide more detail. This is a severe error condition that threatens database integrity and must be corrected immediately. Complete a full database consistency check (DBCC CHECKDB). This error can be caused by many factors; for more information, see SQL Server Books Online.

During redoing of a logged operation in database 'paperbbs7', an error occurred at log record ID (2384385:3223121:189). Typically, the specific failure is previously logged as an error in the Windows Event Log service. Restore the database from a full backup, or repair the database.

오류: 3414, 심각도: 21, 상태: 1.

An error occurred during recovery, preventing the database 'xx' (database ID 6) from restarting. Diagnose the recovery errors and fix them, or restore from a known good backup. If errors are not corrected or expected, contact Technical Support.




------------------------------------########################################------------------------------------------------

일반적인 테스트 시나리오

------------------------------------########################################------------------------------------------------

USE MASTER

GO

 

 

ALTER DATABASE CURRUPTDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE

 

DROP DATABASE CURRUPTDB

 

CREATE DATABASE CURRUPTDB

GO

 

USE CURRUPTDB

GO

 

CREATE TABLE TBLX

(

 C1 VARCHAR(500)

,C2 VARCHAR(1000)

)

GO

 

INSERT INTO TBLX (C1, C2) VALUES ('A', REPLICATE('B',5))

INSERT INTO TBLX (C1, C2) VALUES ('C', REPLICATE('D',5))

 

SELECT * FROM TBLX

C1        C2

A        BBBBB

C        DDDDD

 

DBCC IND (CURRUPTDB, TBLX, -1)

 

PageFID        PagePID        IAMFID        IAMPID        ObjectID        IndexID        PartitionNumber        PartitionID        iam_chain_type        PageType        IndexLevel        NextPageFID        NextPagePID        PrevPageFID        PrevPagePID

1        89        NULL        NULL        245575913        0        1        72057594040549376        In-row data        10        NULL        0        0        0        0

1        80        1        89        245575913        0        1        72057594040549376        In-row data        1        0        0        0        0        0

 

DBCC TRACEON(3604,-1)

 

 

DBCC PAGE (CURRUPTDB, 1, 80, 2)

DBCC PAGE (CURRUPTDB, 1, 80, 3)

 

Memory Dump @0x000000000968A000

 

000000000968A000:   01010000 00800001 00000000 00000400 00000000  ....................

000000000968A014:   00000200 78000000 761f8600 50000000 01000000  ....x...v...P.......

000000000968A028:   22000000 59000000 02000000 00000000 00000000  "...Y...............

000000000968A03C:   00000000 01000000 00000000 00000000 00000000  ....................

000000000968A050:   00000000 00000000 00000000 00000000 30000400  ................0...

000000000968A064:   02000002 000e0013 00414242 42424230 00040002  .........ABBBBB0....

000000000968A078:   00000200 0e001300 43444444 44440000 00000000  ........CDDDDD......

000000000968A08C:   01000000 00000000 00000000 00000000 00000000  ....................

 

5줄 SKIP -> 20 * 5 = 100

9BYTE SKIP -> 100 + 9  = 109

110 BYTE 부터 1BYTE 를 42 로 업데이트 하면 A 가 B로 바뀌게 된다.

(정확하게 제외할 바이트만 계산해서 그 값부터 쓰면된다. 그게 DBCC WRITEPAGE 명령어 이다)

 

-- 단일사용자 모드에서 동작시킨다.

USE MASTER

GO

ALTER DATABASE CURRUPTDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE

 

DBCC WRITEPAGE (N'CURRUPTDB', 1, 80, 109, 1, 0x42, 1);

 

USE CURRUPTDB

GO

 

SELECT * FROM TBLX

 

메시지 824, 수준 24, 상태 2, 줄 64

SQL Server에서 일관성 기반의 논리적인 I/O 오류가 검색되었습니다: 체크섬이 잘못되었습니다(예상: 0xe472b33a, 실제: 0xe5f2b33a).. 파일 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\CURRUPTDB.mdf'의 오프셋 0x000000000a0000에서 데이터베이스 ID 9에 있는 페이지 (1:80)의 읽기 중 이 오류가 발생했습니다. 자세한 내용은 SQL Server 오류 로그 또는 시스템 이벤트 로그의 추가 메시지에서 확인할 수 있습니다. 이는 데이터베이스 무결성을 위협하는 심각한 오류 상태이며 즉시 수정해야 합니다. 전체 데이터베이스 일관성 검사(DBCC CHECKDB)를 완료하십시오. 이 오류는 다양한 요인으로 인해 발생할 수 있습니다. 자세한 내용은 SQL Server 온라인 설명서를 참조하십시오.

 

 

이고 실제 다시 DBCC PAGE 를 보면 값을 바꾸었을때 디스크에 써져있는 예상한 체크섬(예상: 0xe472b33a)과 실제로 다시 계산한 체크섬값 0xe5f2b33a 이 값이 틀려 문제를 일으킨다.

실제값을 리틀엔디언 0x3ab3f2e5 으로 변경 후 이 값으로 바꾸어 주면 문제가 해결된다.

 

체크섬은 항상 OFFSET 값 60에서 시작하니 뭐 쉽게 바꿀수 있다.

DBCC WRITEPAGE (N'CURRUPTDB', 1, 80, 60, 4, 0x3ab3f2e5, 1);

 

DBCC PAGE (CURRUPTDB, 1, 80, 2)

 

Memory Dump @0x0000000010D1A000

 

0000000010D1A000:   01010000 00820001 00000000 00000400 00000000  ....................

0000000010D1A014:   00000200 78000000 761f8600 50000000 01000000  ....x...v...P.......

0000000010D1A028:   22000000 59000000 02000000 00000000 00000000  "...Y...............

0000000010D1A03C:   3ab3f2e5 00000000 00000000 00000000 00000000  :...................

0000000010D1A050:   00000000 00000000 00000000 00000000 30000400  ................0...

0000000010D1A064:   02000002 000e0013 00424242 42424230 00040002  .........BBBBBB0....

0000000010D1A078:   00000200 0e001300 43444444 44440000 00000000  ........CDDDDD......

0000000010D1A08C:   01000000 00000000 00000000 00000000 00000000  ....................

 

 

SELECT * FROM TBLX

C1        C2

B        BBBBB

C        DDDDD







Posted by 보미아빠
, |

https://www.mssqltips.com/sqlservertip/3342/how-to-use-dbcc-checkprimaryfile-to-attach-several-sql-server-databases-in-seconds/



내용은 아래 그냥 카피해 두고,

데이터베이스 파일을을 추가시켜서 만든경우 SSMS 에서 스크립팅하면, 정확하게 같은 번호로 생성되도록 스크립팅 되지 않는다. 그러므로 dbcc checkprimaryfile 명령을 사용해 파일번호를 확인하고 add 명령어로 추가해 주면 가능하다.


USP-V 같은 대형 스토리지 시스템을 가지고 있을경우


SI 백업으로 부터 복구할 때


1. 똑같은 파일 순서로 만든 후 백업 

2. norecovery 모드 복구

3. 대상 파일을 바꿔치기


이 번호가 맞지 않으면 복원할 수 없다.


이때 위 명령을 이용하면 된다.







     

How to use DBCC CHECKPRIMARYFILE to attach several SQL Server databases in seconds

MSSQLTips author Percy Reyes By:   |   Read Comments (15)   |   Related Tips: More > Database Administration
Problem

Have you ever had to attach databases on a SQL Server?  This could be done using the SQL Server Management Studio (SSMS) GUI which is great if it is a one time need, but if you have many databases this could take time.  The other option is to write T-SQL code to do the attach, but this also takes time to write for each database.  Or have you ever run into the situation where you have detached databases that need to be attached to a new server or an existing server?  In this tip I share a way to do this job fast without the need to have to do this manually or write T-SQL code.

Solution

DBCC CHECKPRIMARYFILE is one of the many undocumented SQL Server commands that we can use to do our job as DBAs. Because it is an "undocumented command" we should use caution, but fortunately this is not a dangerous command. This command is used only for reading meta data from the primary database data file on disk and to return information that is very useful, such as the database name, logical names, physical file names and more without having to attach it to an instance of SQL Server.

First of all, I will show the syntax and how to use DBCC CHECKPRIMARYFILE.

Syntax:DBCC CHECKPRIMARYFILE ({'PhysicalFileName'} [,opt={0|1|2|3}])

PhysicalFileName is the full path for the primary database file.

opt=0 - checks if the file a primary database file. 
opt=1 - returns name, size, maxsize, status and path of all files associated to the database.
opt=2 - returns the database name, version and collation.
opt=3 - returns name, status and path of all files associated with the database.

SQL Server DBCC CHECKPRIMARYFILE with Option = 0

First we will use it with zero to check if it is the primary file, if so it will return 1 otherwise 0.

DBCC CHECKPRIMARYFILE('D:\SQLData\AdventureWorksDW2012_Data.mdf',0) WITH NO_INFOMSGS

How to use DBCC CHECKPRIMARYFILE to attach several databases in just a few seconds

Note that the option 0 is the default value, so you don't need to use a value if you only want to check if it is the primary file or not.

DBCC CHECKPRIMARYFILE('D:\SQLData\AdventureWorksDW2012_Data.mdf') WITH NO_INFOMSGS

DBCC CHECKPRIMARYFILE with Option = 1

To check logical name, size, maxsize, status and physical name of all files we use option 1.

DBCC CHECKPRIMARYFILE('D:\SQLData\AdventureWorksDW2012_Data.mdf',1) WITH NO_INFOMSGS

How to use DBCC CHECKPRIMARYFILE to attach several databases in just a few seconds

DBCC CHECKPRIMARYFILE with Option = 2

Checks the database name, version and collation.

DBCC CHECKPRIMARYFILE('D:\SQLData\AdventureWorksDW2012_Data.mdf',2) WITH NO_INFOMSGS

How to use DBCC CHECKPRIMARYFILE to attach several databases in just a few seconds

DBCC CHECKPRIMARYFILE with Option = 3

Checks the logical name, status and path of all files.

DBCC CHECKPRIMARYFILE('D:\SQLData\AdventureWorksDW2012_Data.mdf',3) WITH NO_INFOMSGS

How to use DBCC CHECKPRIMARYFILE to attach several databases in just a few seconds

Use DBCC CHECKPRIMARYFILE Attach SQL Server Database Files

With all of this info in our hands, we can use this to provide a solution to the problem explained at the beginning of this tip.  I will make use of this undocumented command, DBCC CHECKPRIMARYFILE, and combine it with CREATE DATABASE commands to generate a CREATE DATABASE FOR ATTACH statement for all databases we want to put on-line without having to write T-SQL code to do this.

We know that DBCC CHECKPRIMARYFILE needs as an input the physical primary file name, so it important to have this information somewhere. In this case, I will get the physical primary file names into a text file by using the bcp utility as follows:

exec sp_configure 'show advanced options', 1
go
reconfigure with override
go
exec sp_configure 'xp_cmdshell', 1
go
reconfigure with override
go
exec xp_cmdshell 'mkdir c:\temp'
go
exec xp_cmdshell 'bcp "select rtrim(physical_name) from sys.master_files where file_id=1 and db_name(database_id) not in (''master'', ''model'', ''tempdb'', ''distribution'', ''msdb'')"  queryout "C:\temp\MasterDataFiles.txt" -T -c' 
go

Here is what the file looks like after running this.  You could also manually create this data or run a process periodically from your server that gets you this information, so you have it when needed.

list of primary sql server database files

The below code with use the DBCC CHECKPRIMARYFILE command via a cursor to generate the CREATE DATABASE FOR ATTACH code for each database from the list. The following code is easy and self-explanatory by itself.

set nocount on 

declare @TSQLFileName varchar(max)
declare @TSQLCreateDatabase varchar(max)
declare @DatabaseName varchar(512)
declare @LogicalFileName varchar(4000)
declare @PhysicalFileName varchar(4000)
declare @TSQLDBCCPPRIMARYFILE_getdbname varchar(4000)
declare @TSQLDBCCPPRIMARYFILE_getdbfiles varchar(4000)

create table #MasterDataFiles (PhysicalFileName varchar(4000))

--saving physical file names into a txt file 
bulk insert dbo.#masterdatafiles from 'c:\temp\masterdatafiles.txt'
with (rowterminator ='\n');

--reading the database name and all physical file names of each database
declare CursorPhysicalFileName cursor for 
select PhysicalFileName 
from #MasterDataFiles

open CursorPhysicalFileName 

fetch next from CursorPhysicalFileName into @PhysicalFileName

while (@@FETCH_STATUS=0)
begin 
  SET @LogicalFileName=''
  set @TSQLCreateDatabase=''
  set @TSQLFileName=''

  create table #db (property sql_variant, value sql_variant)
  create table #dbfiles(status int, fileid int, name varchar(100), filename varchar(512))

  set @TSQLDBCCPPRIMARYFILE_getdbname='DBCC CHECKPRIMARYFILE ('''+@PhysicalFileName+''', 2)'
  set @TSQLDBCCPPRIMARYFILE_getdbfiles='DBCC CHECKPRIMARYFILE ('''+@PhysicalFileName+''', 3)'

  insert into #db exec (@TSQLDBCCPPRIMARYFILE_getdbname)
  insert into #dbfiles exec (@TSQLDBCCPPRIMARYFILE_getdbfiles)

  select @DatabaseName = cast(value as varchar(512))from #db where property='Database Name'

  -- Now we will create the CREATE DATABASE FOR ATTACH code dynamically
  declare CursorFile cursor for 
  select CAST( [filename] AS VARCHAR(MAX)) 
  from #dbfiles
  
  open CursorFile 
  
  fetch next from CursorFile into @LogicalFileName
  
  while (@@FETCH_STATUS=0)
  begin
   set @TSQLFileName=@TSQLFileName + '(FILENAME=N'''+ 
       LTRIM(RTRIM(@LogicalFileName)) + '''),' + char(13)
   fetch next from CursorFile into @LogicalFileName
  end

  close CursorFile
  deallocate  CursorFile

  set @TSQLCreateDatabase= 'CREATE DATABASE ' + @DatabaseName + ' ON '+ char(13)
     + SUBSTRING(@TSQLFileName, 1,LEN(@TSQLFileName) - 2 ) + CHAR(13)+  'FOR ATTACH;'  
  print @TSQLCreateDatabase

  drop table #dbfiles
  drop table #db

fetch next from CursorPhysicalFileName into @PhysicalFileName
end

close CursorPhysicalFileName
deallocate CursorPhysicalFileName

drop table #MasterDataFiles 

set nocount off

As you can see the output is as follows, which can then be copied and pasted into a new query window to attach all the databases in a few seconds.

How to use DBCC CHECKPRIMARYFILE to attach several databases in just a few seconds

Note that the use of DBCC undocumented commands must be done with extreme caution and first tested in non-production environments.  Many of them can be dangerous and affect your database server if you don't really know how they work.

Next Steps


Posted by 보미아빠
, |

index only script

카테고리 없음 / 2015. 11. 26. 15:39

https://www.mssqltips.com/sqlservertip/3441/script-out-all-sql-server-indexes-in-a-database-using-tsql/


char(13) 10 은 알아서 수정



declare @SchemaName varchar(100)declare @TableName varchar(256)
declare @IndexName varchar(256)
declare @ColumnName varchar(100)
declare @is_unique varchar(100)
declare @IndexTypeDesc varchar(100)
declare @FileGroupName varchar(100)
declare @is_disabled varchar(100)
declare @IndexOptions varchar(max)
declare @IndexColumnId int
declare @IsDescendingKey int
declare @IsIncludedColumn int
declare @TSQLScripCreationIndex varchar(max)
declare @TSQLScripDisableIndex varchar(max)

declare CursorIndex cursor for
select schema_name(t.schema_id) [schema_name], t.name, ix.name,
case when ix.is_unique = 1 then 'UNIQUE ' else '' END
, ix.type_desc,
case when ix.is_padded=1 then 'PAD_INDEX = ON, ' else 'PAD_INDEX = OFF, ' end
+ case when ix.allow_page_locks=1 then 'ALLOW_PAGE_LOCKS = ON, ' else 'ALLOW_PAGE_LOCKS = OFF, ' end
+ case when ix.allow_row_locks=1 then  'ALLOW_ROW_LOCKS = ON, ' else 'ALLOW_ROW_LOCKS = OFF, ' end
+ case when INDEXPROPERTY(t.object_id, ix.name, 'IsStatistics') = 1 then 'STATISTICS_NORECOMPUTE = ON, ' else 'STATISTICS_NORECOMPUTE = OFF, ' end
+ case when ix.ignore_dup_key=1 then 'IGNORE_DUP_KEY = ON, ' else 'IGNORE_DUP_KEY = OFF, ' end
+ 'SORT_IN_TEMPDB = OFF, FILLFACTOR =' + CAST(ix.fill_factor AS VARCHAR(3)) AS IndexOptions
, ix.is_disabled , FILEGROUP_NAME(ix.data_space_id) FileGroupName
from sys.tables t
inner join sys.indexes ix on t.object_id=ix.object_id
where ix.type>0 and ix.is_primary_key=0 and ix.is_unique_constraint=0 --and schema_name(tb.schema_id)= @SchemaName and tb.name=@TableName
and t.is_ms_shipped=0 and t.name<>'sysdiagrams'
order by schema_name(t.schema_id), t.name, ix.name

open CursorIndex
fetch next from CursorIndex into  @SchemaName, @TableName, @IndexName, @is_unique, @IndexTypeDesc, @IndexOptions,@is_disabled, @FileGroupName

while (@@fetch_status=0)
begin
declare @IndexColumns varchar(max)
declare @IncludedColumns varchar(max)

set @IndexColumns=''
set @IncludedColumns=''

declare CursorIndexColumn cursor for
  select col.name, ixc.is_descending_key, ixc.is_included_column
  from sys.tables tb
  inner join sys.indexes ix on tb.object_id=ix.object_id
  inner join sys.index_columns ixc on ix.object_id=ixc.object_id and ix.index_id= ixc.index_id
  inner join sys.columns col on ixc.object_id =col.object_id  and ixc.column_id=col.column_id
  where ix.type>0 and (ix.is_primary_key=0 or ix.is_unique_constraint=0)
  and schema_name(tb.schema_id)=@SchemaName and tb.name=@TableName and ix.name=@IndexName
  order by ixc.index_column_id

open CursorIndexColumn
fetch next from CursorIndexColumn into  @ColumnName, @IsDescendingKey, @IsIncludedColumn

while (@@fetch_status=0)
begin
  if @IsIncludedColumn=0
   set @IndexColumns=@IndexColumns + @ColumnName  + case when @IsDescendingKey=1  then ' DESC, ' else  ' ASC, ' end
  else
   set @IncludedColumns=@IncludedColumns  + @ColumnName  +', '

  fetch next from CursorIndexColumn into @ColumnName, @IsDescendingKey, @IsIncludedColumn
end

close CursorIndexColumn
deallocate CursorIndexColumn

set @IndexColumns = substring(@IndexColumns, 1, len(@IndexColumns)-1)
set @IncludedColumns = case when len(@IncludedColumns) >0 then substring(@IncludedColumns, 1, len(@IncludedColumns)-1) else '' end
--  print @IndexColumns
--  print @IncludedColumns

set @TSQLScripCreationIndex =''
set @TSQLScripDisableIndex =''
set @TSQLScripCreationIndex='CREATE '+ @is_unique  +@IndexTypeDesc + ' INDEX ' +QUOTENAME(@IndexName)+' ON ' + QUOTENAME(@SchemaName) +'.'+ QUOTENAME(@TableName)+ '('+@IndexColumns+') '+
  case when len(@IncludedColumns)>0 then CHAR(13) +'INCLUDE (' + @IncludedColumns+ ')' else '' end + CHAR(13)+'WITH (' + @IndexOptions+ ') ON ' + QUOTENAME(@FileGroupName) + ';' 

if @is_disabled=1
  set  @TSQLScripDisableIndex=  CHAR(13) +'ALTER INDEX ' +QUOTENAME(@IndexName) + ' ON ' + QUOTENAME(@SchemaName) +'.'+ QUOTENAME(@TableName) + ' DISABLE;' + CHAR(13)

print @TSQLScripCreationIndex
print @TSQLScripDisableIndex

fetch next from CursorIndex into  @SchemaName, @TableName, @IndexName, @is_unique, @IndexTypeDesc, @IndexOptions,@is_disabled, @FileGroupName

end
close CursorIndex
deallocate CursorIndex

Posted by 보미아빠
, |

string.format

카테고리 없음 / 2015. 11. 21. 18:31

http://slaner.tistory.com/92

Posted by 보미아빠
, |

vs 테마바꾸기

카테고리 없음 / 2015. 11. 11. 15:49

내가 원하는건 이거였어...

http://korbillgates.tistory.com/32


win10 에서 .net framework 에러가 나면 아래와 같이 하면 된다. -_- 지저분해....


Heres what i did, worked like a charm.
1. Create a shortcut to the Vs2013 VSIX Installer at "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\VSIXInstaller.exe"
2. Download the Extension Manually.
3. Open in your favorite Zip program and copy the "extension.vsixmanifest" out.
4. Open in a text editor and comment out the "<Dependency Id="Microsoft.Framework.NDP" DisplayName="Microsoft .NET Framework" Version="4.5" />" line, its standard XML and save.
5. Copy modified file in to VSIX package overwriting the first.
6. Install (drag+drop over our Installer shortcut)





2. http://studiostyl.es/

위 주소에서 마음에 드는 색상을 선택해서 다운로드 받는다. ( 확장자가 vssettings 이다. )

 

3. 내문서\Visual Studio 2010\Settings 폴더에 보면 CurrentSettings.vssettings 파일이 있는데, 일단 그 파일을 백업해두고, 다운로드 받은 파일을 CurrentSettings.vssettings 로 바꿔놓는다.

 

4. Visual Studio 를 실행시키면 테마가 바뀌어 있다.


Posted by 보미아빠
, |

단위변환

카테고리 없음 / 2015. 11. 4. 18:03

=IF(D2="MB",C2,IF(D2="GB",C2*POWER(10,3),IF(D2="TB",C2*POWER(10,6), ) ) )

Posted by 보미아빠
, |

최근에 달린 댓글

최근에 받은 트랙백

글 보관함