GVKun编程网logo

SQL Server 2008 R2:匹配字符串(sql语句匹配字符串)

20

在本文中,我们将详细介绍如何在SQLServerManagementStudio中将1设置为0'-1关系的各个方面,并为您提供关于sql1=0的相关解答,同时,我们也将为您带来关于c#–在SQLSer

在本文中,我们将详细介绍如何在SQL Server Management Studio中将1设置为0'-1关系的各个方面,并为您提供关于sql 1=0的相关解答,同时,我们也将为您带来关于c# – 在SQL Server Management Studio中创建一个新菜单项、SQL Server Management Studio中'go'附近的语法不正确、SQL Server 在Management Studio中使用Web浏览器、sql-server – SQL Server Management Studio中的“收藏夹”或“宏”?的有用知识。

本文目录一览:

如何在SQL Server Management Studio中将1设置为0'-1关系(sql 1=0)

如何在SQL Server Management Studio中将1设置为0'-1关系(sql 1=0)

我有表:

Users{UserId ...}Professors{UserId ...}

UserId在两个表中都设置为PK,并建立了1:1关系。

但是,如果我尝试插入新用户,则无法使用,因为它也需要在Professor表中插入。

我想使一个用户在Professor表中只能有1条记录,但我也想使其不必在Professor表中存在(我不想让所有用户都教授:))。

如何在SQL Server Management Studio中将1设置为(0 … 1)关系?

我知道将强制执行键约束设置为NO并不是解决方案:)

答案1

如果您有以下要求:

  • 用户可以是教授,也可以不是
  • 教授永远是用户

那么你是正确的,那是一种1 :: 0..1关系。在SQL中,可以这样实现:

CREATE TABLE Users  ( UserId INT NOT NULL  , ...  , PRIMARY KEY (UserId)  ) ;CREATE TABLE Professors  ( UserId INT NOT NULL  , ...  , PRIMARY KEY (UserId)  , FOREIGN KEY (UserId)      REFERENCES Users (UserId)  ) ;

根据您的描述,您可能已经以相反的顺序定义了外键约束。

c# – 在SQL Server Management Studio中创建一个新菜单项

c# – 在SQL Server Management Studio中创建一个新菜单项

是否可以在sql Server 2008 Management Studio中创建新的菜单项?

例如,当您右键单击数据库时,会出现一个选项列表(新数据库,新查询…).

是否可以在该列表中添加新项目并在单击该按钮时实现一些C#功能?

解决方法

从 MSDN起.

在菜单中添加新项
向菜单添加新项目

  1. On the Tools menu,click Options.
  2. In the Customize dialog Box,on the Commands tab,click New Menu.
  3. On the Commands Box,drag New Menu to the menu bar and drop it where you want the new menu to appear.
  4. On the menu,right-click New Menu,and in the Name Box,type a name for the new menu.
  5. In the Customize dialog Box,select category such as File,and select a command such as Open File. Drag the command to the new menu. As you point to the new menu,the menu will expand. Drop the command onto the expanded menu.
  6. In the Customize dialog Box,click Close.

SQL Server Management Studio中'go'附近的语法不正确

SQL Server Management Studio中'go'附近的语法不正确

如何解决SQL Server Management Studio中''go''附近的语法不正确?

sql Server Management Studio无法处理某些不可打印的字符。

检查换行符,可能您使用的是Linux(LF)或Mac样式(CR),而不是Windows样式(CR和LF)。您可以使用任何高级文本编辑器进行检查,例如Notepad++路

解决方法

执行以下SQL:

drop function f
go

在MS Sql Server Management Studio中,给我这个解析错误:

消息102,级别15,状态1,第1行’go’附近的语法不正确。

为什么?

如果我打开一个新选项卡并将SQL复制/粘贴到其中,它也会失败。但是,如果我打开一个新选项卡并完全重新输入SQL,它就可以正常工作。

SQL Server 在Management Studio中使用Web浏览器

SQL Server 在Management Studio中使用Web浏览器

我们在sql Server Management Studio中写sql 的时候,避免不了在浏览器和SSMS两者之间频繁切换,并浪费时间,殊不知,SSMS中自带有一个Web浏览器,和操作查询标签是一样的,非常的方便。

在SSMS中点击“视图”》“其他窗口”》“Web浏览器”,就会打开如下图所示:

https://files.jb51.cc/file_images/article/201605/2016521165126828.jpg

这样我们就可以在SSMS中打开web浏览器进行查询信息了,是不是很方便。

上面这个,还是避免不了在浏览器标签和查询标签之间来回切换,如果打开的浏览器标签过多,我们的显示器还有限,就会把我们的查询标签给挤到下面去,就不好找了。有什么办法可以解决呢?

办法是有的,在浏览器标签鼠标“右击”,会出现下图所示:

https://files.jb51.cc/file_images/article/201605/2016521165133621.jpg

我们选择“新建垂直选项卡组”,就会把查询标签和浏览器标签分开了,如下图:

https://files.jb51.cc/file_images/article/201605/2016521165144069.jpg

这样,在浏览器标签组打开多个标签,并不影响查询标签组,我们就可以一边写sql,一边查信息,是不是更方便了!

sql-server – SQL Server Management Studio中的“收藏夹”或“宏”?

sql-server – SQL Server Management Studio中的“收藏夹”或“宏”?

我有一些数据库,我总是使用sql Server Management Studio.我希望能够创建一个工具栏按钮或键盘快捷键,自动打开一个新的查询窗口(在当前的SSMS实例中)并连接到给定的(可能已注册)数据库.而已.这就是我所需要的一切.这个烟灰缸,桨游戏和遥控器.这就是我所需要的一切.

就像现在一样,我必须展开对象资源管理器,折叠/展开两到八棵树,右键单击我的数据库,然后选择“新建查询”.我认为没办法做到这一点,这可能每天节省我30-60秒,这至少值1美元和NINE CENTS.

解决方法

我是 SSMSBoost加载项的开发人员,它完全符合您的需求:允许管理首选服务器/数据库列表,并通过工具栏上的自定义ComboBox快速切换它们,您也可以说,如果您想要所有服务器在启动时在ObjectExplorer中打开,如果应为它们打开一个新的查询窗口(每服务器设置).

SSMSBoost还允许您定义别名(而不是server8273128> MainServer,server231232> BackupServer等.)
它有更多功能 – 但它们超出了本主题的范围.

查看图片 – 您可以看到快速连接交换机组合框与来自首选连接的一些服务器,“SSMSBoostDemoServer” – 是服务器的别名,下一个名称 – 是原始的.

还有一件事 – 免费版提供加载项.

关于如何在SQL Server Management Studio中将1设置为0'-1关系sql 1=0的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于c# – 在SQL Server Management Studio中创建一个新菜单项、SQL Server Management Studio中'go'附近的语法不正确、SQL Server 在Management Studio中使用Web浏览器、sql-server – SQL Server Management Studio中的“收藏夹”或“宏”?等相关内容,可以在本站寻找。

此处将为大家介绍关于SQL Server 2016中的Json函数的详细内容,并且为您解答有关sql server json 解析的相关问题,此外,我们还将为您介绍关于java – Sql Server 2016:为SQL Server连接启用TLS 1.2、jMeter ServerAgent在Windows Server 2016中崩溃、jquery – SQL Server中的JSON数据处理、SQL Server 2012 R2升级到SQL Server 2016无法正常启动数据库服务解决方案的有用信息。

本文目录一览:

SQL Server 2016中的Json函数(sql server json 解析)

SQL Server 2016中的Json函数(sql server json 解析)

这是我的JSON

[{"type": "FormBlock","id": "07bac163-1765-1fee-dba7-6668f8d8507f","x": 50,"y": 57,"width": 120,"height": 50,"alpha": 1,"angle": 0,"userData": {"schema":"{"form":[{"id":"1493828935122"},{"id":"1495115355556"}]}]

我的查询

SELECT JSON_VALUE((SELECT JSON_QUERY([Schema].[schema],''$[0]'')                        FROM [dbo].[Schema] WHERE objecttype=''test''),''$.userData.schema.form[0].id'')

[Schema]。[schema]:具有列[schema]的表[Schema](包含json)

我可以获取userData.schema数据,但是如果我想拥有userData.schema.form.id,它就不会工作。为什么?

答案1

假设您有以下文档存储在SQL中:

    CREATE TABLE JSONTable ( ID int IDENTITY (1,1) PRIMARY KEY CLUSTERED,JSONDocument nvarchar(max) )INSERT INTO JSONTableSELECT ''{            "FilmDetails":{                "ProductNumber":"9912088751",                "Title":"Brave",                "Type":"Movie",                "Runtime":93,                "ReleaseYear":2012,                "Synopses":[                    {                        "Locale":"en",                        "Text":"Princess Merida uses her bravery and archery skills to battle a curse and restore peace..."                    },                    {                        "Locale":"de",                        "Text":"Animiert"                    },                    {                        "Locale":"fr",                        "Text":"Au coeur des contr茅es sauvages d脡cosse, Merida, la fille du roi Fergus et de la reine Elinor..."}],                "Assets":[                    {                        "Name":"Stickers",                        "AssetType":"Stickers",                        "FileType":"PDF",                        "Location":"http://media.brave.stickers.pdf",                        "Locale":"en-US"                    },                    {                        "Name":"Trailer - WMV",                        "AssetType":"Trailer - WMV",                        "FileType":"Video",                        "Location":"http://youtu.be/Shg79Shgn",                        "Locale":"en-US"                    }]                }            }''

您可以像这样查询数组:

SELECT     JSON_VALUE(JSONDocument, ''$.FilmDetails.ProductNumber'') as ProductNumber    ,JSON_VALUE(JSONDocument, ''$.FilmDetails.Title'') as Title    ,JSON_VALUE(JSONDocument, ''$.FilmDetails.Type'') as ContentType    ,JSON_VALUE(JSONDocument, ''$.FilmDetails.Runtime'') as Runtime    ,JSON_VALUE(JSONDocument, ''$.FilmDetails.ReleaseYear'') as ReleaseYear    ,Locale    ,SynopsesText    ,Name AS AssetName    ,FileType AS AssetFileType    ,[Location] AS AssetLocationFROM JSONTableCROSS APPLY OPENJSON(JSONDocument, ''$.FilmDetails.Synopses'')WITH (        Locale varchar(3) ''$.Locale''      ,SynopsesText nvarchar(2000) ''$.Text'') CROSS APPLY OPENJSON(JSONDocument, ''$.FilmDetails.Assets'')WITH (        Name varchar(25) ''$.Name''      ,FileType varchar(25) ''$.FileType''    ,[Location] nvarchar(500) ''$.Location'' ) WHERE JSON_VALUE(JSONDocument, ''$.FilmDetails.Title'') LIKE ''%Brave%''    AND Locale = ''en''    AND FileType = ''video''

这是我不久前写的一篇博客文章,但我认为它可以为您提供所需的内容,可以查询数组。

java – Sql Server 2016:为SQL Server连接启用TLS 1.2

java – Sql Server 2016:为SQL Server连接启用TLS 1.2

我在 Windows 2012 R2上运行sql Server 2016并且我应用了TLSv1.2支持的补丁并重新启动了VM,https://support.microsoft.com/en-us/help/3135244/tls-1-2-support-for-microsoft-sql-server我确实看到在sql Server VM上使用IISCrypto工具启用了TLS 1.2

我们有Java 8 Web应用程序,我们强制Web应用程序只使用TLS1.2使用JVM参数-Djdk.tls.client.protocols =“TLSv1.2”(如果我删除此JVM参数应用程序连接到sql server罚款),但我们看到下面的错误虽然为sql服务器启用了TLSv1.2

org.apache.commons.dbcp.sqlnestedException: Cannot create PoolableConnectionFactory (The driver Could not establish a secure connection to sql Server by using Secure Sockets Layer (SSL) encryption. Error: "Server chose TLSv1,but that protocol version is not enabled or not supported by the client.". ClientConnectionId:7564b6a1-60c0-4a24-8baa-7bd21f9512cf)

我们还有一个.Net 2.0 Windows服务(在注册表中只启用了TLSv1.2),它也无法连接到sql Server 2016

System.Data.OleDb.OleDbException: [dbnETLIB][Connectionopen (SECCreateCredentials()).]SSL Security error.
at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr,OleDbConnection connection)
at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionoptions options,Object poolGroupProviderInfo,DbConnectionPool pool,DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection,DbConnectionPoolGroup poolGroup)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection,DbConnectionFactory connectionFactory)
at System.Data.OleDb.OleDbConnection.open()

但是,如果我在注册表中启用SSL3和TLS1.0,.Net 2.0 Windows服务可以很好地连接到sql Server 2016.

我怀疑,问题是sql Server没有使用TLSv1.2,虽然在sql Server VM上启用了TLSv1.2,如果有更多的配置或补丁需要应用于sql Server以支持TLSv1.2,有人可以帮助我吗?

解决方法

Microsoft Windows Server存储有关Windows Server支持的不同安全性增强通道协议的信息.此信息存储在以下注册表项中:

HKey_Local_Machine\System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols

通常,此键包含以下子项:

PCT 1.0,SSL 2.0,SSL 3.0,TLS 1.0 …

每个密钥都包含有关密钥协议的信息.可以在服务器上启用这些协议中的任何一个.为此,您需要在协议的服务器子项中创建新的DWORD值.您将DWORD值设置为“1”.

重要说明:在修改注册表之前备份注册表.然后,您可以在出现问题时还原注册表.

要启用TLS 1.x协议,请执行以下步骤:

单击“开始”,单击“运行”,键入regedt32或键入regedit,然后单击“确定”.
在注册表编辑器中,找到以下注册表项:

HKey_Local_Machine\System\CurrentControlSet\Control\SecurityProviders \SCHANNEL\Protocols\TLS 1.x\Server

在“编辑”菜单上,单击“添加值”.
在“数据类型”列表中,单击“DWORD”.
在“值名称”框中,键入“已启用”,然后单击“确定”.

注意如果存在此值,请双击该值以编辑其当前值.

在二进制编辑器中键入11111111,将新键的值设置为“1”.
单击确定.重启电脑.

希望这可以帮助…

jMeter ServerAgent在Windows Server 2016中崩溃

jMeter ServerAgent在Windows Server 2016中崩溃

这听起来像是SIGAR bug,但不幸的是您无能为力(除非您想调查sigar-amd64-winnt.dll的问题,实施解决方案,将其贡献给SIGAR上游并更新JMeter PerfMon固定版本的插件)

同时,您可以考虑将SSHMon Samples Collector作为解决方法,请查看How to Monitor Server Resource Utilization with JMeter’s SSHMon Listener文章以了解更多详细信息

jquery – SQL Server中的JSON数据处理

jquery – SQL Server中的JSON数据处理

我有一个Json字符串.我想从那个Json字符串中获取价值.

这是我的json字符串
{ “纬度”: “22.5712854”},{ “经度”: “88.4266847”}

我只想使用TSQL查询来获得纬度和经度.

解决方法

在Tsql中没有解析 JSON的本机方法.但Phil Factor在sql函数中创建了自己的配对JSON的实现.有关它的更多信息,请参阅文章: Consuming JSON Strings in SQL Server中的简单谈话博客

Aslo Ric Vander Ark创造了他自己的功能,但我没有测试它.您可以在文章:A Function to Split JSON Data上阅读更多内容

SQL Server 2012 R2升级到SQL Server 2016无法正常启动数据库服务解决方案

SQL Server 2012 R2升级到SQL Server 2016无法正常启动数据库服务解决方案

原定周末把公司的TFS升级到2018,由于TFS 2018需要SQL Server至少是2016以上版本,所以还需要将原来的SQL Server 2012 R2一并升级。今天早上负责的同事告诉我升级失败了。SQL Server 2016的数据库服务无法正常启动。他期间还尝试修复了一次SQL Server 2016,仍然提示无法正常启动数据库服务。错误提示如下:

Action required:
Use the following information to resolve the error, and then try the setup process again.

Feature failure reason:
An error occurred during the setup process of the feature.

Error details:
§ Error installing SQL Server Database Engine Services Instance Features
The service did not respond to the start or control request in a timely fashion.
Error code: 0x80004005
Visit http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=13.0.1711.0&EvtType=0xDC112D1C%400xDC80C325&EvtType=0xDC112D1C%400xDC80C325 to get help on troubleshooting.
Warning details:
§ Missing or unspecified settings that were configured to default values:
Service SID support has been enabled on the service.

给予的帮助不是很大,先打开事件查看器找找有什么错误信息:

Windows cannot access the file  for one of the following reasons: there is a problem with the network connection, the disk that the file is stored on, or the storage drivers installed on this computer; or the disk is missing. Windows closed the program SQL Server Windows NT - 64 Bit because of this error.

Program: SQL Server Windows NT - 64 Bit
File: 

The error value is listed in the Additional Data section.
User Action
1. Open the file again. This situation might be a temporary problem that corrects itself when the program runs again.
2. If the file still cannot be accessed and
    - It is on the network, your network administrator should verify that there is not a problem with the network and that the server can be contacted.
    - It is on a removable disk, for example, a floppy disk or CD-ROM, verify that the disk is fully inserted into the computer.
3. Check and repair the file system by running CHKDSK. To run CHKDSK, click Start, click Run, type CMD, and then click OK. At the command prompt, type CHKDSK /F, and then press ENTER.
4. If the problem persists, restore the file from a backup copy.
5. Determine whether other files on the same disk can be opened. If not, the disk might be damaged. If it is a hard disk, contact your administrator or computer hardware vendor for further assistance.

Additional Data
Error value: 00000000
Disk type: 0

错误提示我们可以选择运行一下磁盘检查,凭经验觉得还是再看一次SQL Server 2016的安装日志,Summary内容如下:

Overall summary:
  Final result:                  Failed: see details below
  Exit code (Decimal):           -2068119551
  Start time:                    2018-07-23 09:27:05
  End time:                      2018-07-23 09:42:09
  Requested action:              Repair

Setup completed with required actions for features.
Troubleshooting information for those features:
  Next step for SQLEngine:       Use the following information to resolve the error, and then try the setup process again.
  Next step for FullText:        Use the following information to resolve the error, and then try the setup process again.
  Next step for AS:              Use the following information to resolve the error, and then try the setup process again.


Machine Properties:
  Machine name:                  SQL
  Machine processor count:       4
  OS version:                    Microsoft Windows Server 2012 Datacenter (6.2.9200)
  OS service pack:               
  OS region:                     United States
  OS language:                   English (United States)
  OS architecture:               x64
  Process architecture:          64 Bit
  OS clustered:                  No

Product features discovered:
  Product              Instance             Instance ID                    Feature                                  Language             Edition              Version         Clustered  Configured
  SQL Server 2012      MSSQL2               MSSQL11.MSSQL2                 Database Engine Services                 1033                 Enterprise Edition   11.2.5058.0     No         Yes       
  SQL Server 2012      MSSQL2               MSSQL11.MSSQL2                 Full-Text and Semantic Extractions for Search 1033                 Enterprise Edition   11.2.5058.0     No         Yes       
  SQL Server 2012                                                          SSMS                                     1033                 Enterprise Edition   11.2.5058.0     No         Yes       
  SQL Server 2012                                                          Adv_SSMS                                 1033                 Enterprise Edition   11.2.5058.0     No         Yes       
  SQL Server 2016      MSSQLSERVER          MSSQL13.MSSQLSERVER            Database Engine Services                 1033                 Enterprise Edition   13.0.1601.5     No         Yes       
  SQL Server 2016      MSSQLSERVER          MSSQL13.MSSQLSERVER            Full-Text and Semantic Extractions for Search 1033                 Enterprise Edition   13.0.1601.5     No         Yes       
  SQL Server 2016      MSSQLSERVER          MSAS13.MSSQLSERVER             Analysis Services                        1033                 Enterprise Edition   13.0.1601.5     No         Yes       
  SQL Server 2016      MSSQLSERVER          MSRS13.MSSQLSERVER             Reporting Services - Native              1033                 Enterprise Edition   13.0.1601.5     No         Yes       

Package properties:
  Description:                   Microsoft SQL Server 2016 
  ProductName:                   SQL Server 2016
  Type:                          RTM
  Version:                       13
  SPLevel:                       0
  Installation location:         I:\x64\setup\
  Installation edition:          Enterprise

User Input Settings:
  ACTION:                        Repair
  AGTDOMAINGROUP:                <empty>
  AGTSVCACCOUNT:                 NT Service\SQLSERVERAGENT
  AGTSVCPASSWORD:                <empty>
  AGTSVCSTARTUPTYPE:             Manual
  ASCONFIGDIR:                   Config
  ASSVCACCOUNT:                  NT Service\MSSQLServerOLAPService
  ASSVCPASSWORD:                 <empty>
  ASTELSVCACCT:                  NT Service\SSASTELEMETRY
  ASTELSVCPASSWORD:              <empty>
  ASTELSVCSTARTUPTYPE:           Automatic
  CLTSTARTUPTYPE:                0
  CLTSVCACCOUNT:                 <empty>
  CLTSVCPASSWORD:                <empty>
  CONFIGURATIONFILE:             C:\Program Files\Microsoft SQL Server\130\Setup Bootstrap\Log\20180723_092704\ConfigurationFile.ini
  CTLRSTARTUPTYPE:               0
  CTLRSVCACCOUNT:                <empty>
  CTLRSVCPASSWORD:               <empty>
  ENU:                           true
  EXTSVCACCOUNT:                 <empty>
  EXTSVCPASSWORD:                <empty>
  FAILOVERCLUSTERGROUP:          <empty>
  FAILOVERCLUSTERNETWORKNAME:    <empty>
  FTSVCACCOUNT:                  NT Service\MSSQLFDLauncher
  FTSVCPASSWORD:                 <empty>
  HELP:                          false
  IACCEPTROPENLICENSETERMS:      false
  INDICATEPROGRESS:              false
  INSTANCENAME:                  MSSQLSERVER
  ISSVCACCOUNT:                  NT AUTHORITY\Network Service
  ISSVCPASSWORD:                 <empty>
  ISSVCSTARTUPTYPE:              Automatic
  ISTELSVCACCT:                  <empty>
  ISTELSVCPASSWORD:              <empty>
  ISTELSVCSTARTUPTYPE:           0
  MRCACHEDIRECTORY:              
  QUIET:                         false
  QUIETSIMPLE:                   false
  SQLSVCACCOUNT:                 NT Service\MSSQLSERVER
  SQLSVCPASSWORD:                <empty>
  SQLTELSVCACCT:                 NT Service\SQLTELEMETRY
  SQLTELSVCPASSWORD:             <empty>
  SQLTELSVCSTARTUPTYPE:          Automatic
  SUPPRESSPRIVACYSTATEMENTNOTICE: false
  UIMODE:                        Normal
  X86:                           false

  Configuration file:            C:\Program Files\Microsoft SQL Server\130\Setup Bootstrap\Log\20180723_092704\ConfigurationFile.ini

Detailed results:
  Feature:                       Database Engine Services
  Status:                        Failed: see logs for details
  Reason for failure:            An error occurred during the setup process of the feature.
  Next Step:                     Use the following information to resolve the error, and then try the setup process again.
  Component name:                SQL Server Database Engine Services Instance Features
  Component error code:          0x80004005
  Error description:             The service did not respond to the start or control request in a timely fashion.
  Error help link:               http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=13.0.1711.0&EvtType=0xDC112D1C%400xDC80C325&EvtType=0xDC112D1C%400xDC80C325

  Feature:                       Full-Text and Semantic Extractions for Search
  Status:                        Failed: see logs for details
  Reason for failure:            An error occurred for a dependency of the feature causing the setup process for the feature to fail.
  Next Step:                     Use the following information to resolve the error, and then try the setup process again.
  Component name:                SQL Server Database Engine Services Instance Features
  Component error code:          0x80004005
  Error description:             The service did not respond to the start or control request in a timely fashion.
  Error help link:               http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=13.0.1711.0&EvtType=0xDC112D1C%400xDC80C325&EvtType=0xDC112D1C%400xDC80C325

  Feature:                       Reporting Services - Native
  Status:                        Passed

  Feature:                       Analysis Services
  Status:                        Failed: see logs for details
  Reason for failure:            An error occurred during the setup process of the feature.
  Next Step:                     Use the following information to resolve the error, and then try the setup process again.
  Component name:                SQL Server Analysis Services
  Component error code:          0x84BB0001
  Error description:             The service did not respond to the start or control request in a timely fashion.
  Error help link:               http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=13.0.1711.0&EvtType=0xDC112D1C%400xDC80C325&EvtType=0xDC112D1C%400xDC80C325

  Feature:                       SQL Browser
  Status:                        Passed

  Feature:                       SQL Writer
  Status:                        Passed

  Feature:                       SQL Client Connectivity
  Status:                        Passed

  Feature:                       SQL Client Connectivity SDK
  Status:                        Passed

  Feature:                       Setup Support Files
  Status:                        Passed

Rules with failures:

Global rules:

There are no scenario-specific rules.

Rules report file:               C:\Program Files\Microsoft SQL Server\130\Setup Bootstrap\Log\20180723_092704\SystemConfigurationCheck_Report.htm

The following warnings were encountered while configuring settings on your SQL Server.  These resources / settings were missing or invalid so default values were used in recreating the missing resources.  Please review to make sure they don’t require further customization for your applications:

Service SID support has been enabled on the service.

大致意思就是数据库服务无法正常启动,更要命的是Error Help Link点击打开后自动回到了微软官网,没有缩小错误范围的价值。于是继续查看Detail.txt,文件内容比较多只把error和exception作为搜索关键字定位,下面只贴出相关信息(期间学习了一下:查看和阅读 SQL Server 安装程序日志文件):

(01) 2018-07-23 09:32:14 Slp: The configuration failure category of current exception is ConfigurationFailure
(01) 2018-07-23 09:32:14 Slp: Configuration action failed for feature SQL_Engine_Core_Inst during timing ConfigRC and scenario ConfigRC.
(01) 2018-07-23 09:32:14 Slp: System.ComponentModel.Win32Exception (0x80004005): The service did not respond to the start or control request in a timely fashion.
(01) 2018-07-23 09:32:14 Slp:    at Microsoft.SqlServer.Configuration.Sco.Service.StartService(String[] startParams)
(01) 2018-07-23 09:32:14 Slp:    at Microsoft.SqlServer.Configuration.SqlEngine.SqlServerServiceSCM.StartSqlServer(String[] parameters, Boolean withFailpoint)
(01) 2018-07-23 09:32:14 Slp:    at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.UpgradeSQLServerSystemDatabases(EffectiveProperties properties, Boolean isConfiguringTemplateDBs, Boolean fShutdown)
(01) 2018-07-23 09:32:14 Slp:    at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.Upgrade_ConfigRC(Version fromVersion, EffectiveProperties properties, Boolean shutdownRightAway)
(01) 2018-07-23 09:32:14 Slp:    at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.RepairFailedUpgrade(ConfigActionTiming timing, Dictionary`2 actionData)
(01) 2018-07-23 09:32:14 Slp:    at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.Repair(ConfigActionTiming timing, Dictionary`2 actionData, PublicConfigurationBase spcb)
(01) 2018-07-23 09:32:14 Slp:    at Microsoft.SqlServer.Configuration.SqlConfigBase.PrivateConfigurationBase.Execute(ConfigActionScenario scenario, ConfigActionTiming timing, ConfigBaseAction action, Dictionary`2 actionData, PublicConfigurationBase spcbCurrent)
(01) 2018-07-23 09:32:14 Slp:    at Microsoft.SqlServer.Configuration.SqlConfigBase.SqlFeatureConfigBase.Execute(ConfigActionScenario scenario, ConfigActionTiming timing, ConfigBaseAction action, Dictionary`2 actionData, PublicConfigurationBase spcbCurrent)
(01) 2018-07-23 09:32:14 Slp:    at Microsoft.SqlServer.Configuration.SqlConfigBase.SlpConfigAction.ExecuteAction(String actionId)
(01) 2018-07-23 09:32:14 Slp:    at Microsoft.SqlServer.Configuration.SqlConfigBase.SlpConfigAction.Execute(String actionId, TextWriter errorStream)
(01) 2018-07-23 09:32:14 Slp: The following is an exception stack listing the exceptions in outermost to innermost order
(01) 2018-07-23 09:32:14 Slp: Inner exceptions are being indented
(01) 2018-07-23 09:32:14 Slp: 
(01) 2018-07-23 09:32:14 Slp: Exception type: System.ComponentModel.Win32Exception
(01) 2018-07-23 09:32:14 Slp:     Message: 
(01) 2018-07-23 09:32:14 Slp:         The service did not respond to the start or control request in a timely fashion.
(01) 2018-07-23 09:32:14 Slp:         
(01) 2018-07-23 09:32:14 Slp:     HResult : 0x80004005
(01) 2018-07-23 09:32:14 Slp:     Error : 1053
(01) 2018-07-23 09:32:14 Slp:     Data: 
(01) 2018-07-23 09:32:14 Slp:       SQL.Setup.FailureCategory = ConfigurationFailure
(01) 2018-07-23 09:32:14 Slp:       WatsonConfigActionData = REPAIR@CONFIGRC@SQL_ENGINE_CORE_INST
(01) 2018-07-23 09:32:14 Slp:       WatsonExceptionFeatureIdsActionData = System.String[]
(01) 2018-07-23 09:32:14 Slp:     Stack: 
(01) 2018-07-23 09:32:14 Slp:         at Microsoft.SqlServer.Configuration.Sco.Service.StartService(String[] startParams)
(01) 2018-07-23 09:32:14 Slp:         at Microsoft.SqlServer.Configuration.SqlEngine.SqlServerServiceSCM.StartSqlServer(String[] parameters, Boolean withFailpoint)
(01) 2018-07-23 09:32:14 Slp:         at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.UpgradeSQLServerSystemDatabases(EffectiveProperties properties, Boolean isConfiguringTemplateDBs, Boolean fShutdown)
(01) 2018-07-23 09:32:14 Slp:         at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.Upgrade_ConfigRC(Version fromVersion, EffectiveProperties properties, Boolean shutdownRightAway)
(01) 2018-07-23 09:32:14 Slp:         at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.RepairFailedUpgrade(ConfigActionTiming timing, Dictionary`2 actionData)
(01) 2018-07-23 09:32:14 Slp:         at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.Repair(ConfigActionTiming timing, Dictionary`2 actionData, PublicConfigurationBase spcb)
(01) 2018-07-23 09:32:14 Slp:         at Microsoft.SqlServer.Configuration.SqlConfigBase.PrivateConfigurationBase.Execute(ConfigActionScenario scenario, ConfigActionTiming timing, ConfigBaseAction action, Dictionary`2 actionData, PublicConfigurationBase spcbCurrent)
(01) 2018-07-23 09:32:14 Slp:         at Microsoft.SqlServer.Configuration.SqlConfigBase.SqlFeatureConfigBase.Execute(ConfigActionScenario scenario, ConfigActionTiming timing, ConfigBaseAction action, Dictionary`2 actionData, PublicConfigurationBase spcbCurrent)
(01) 2018-07-23 09:32:14 Slp:         at Microsoft.SqlServer.Configuration.SqlConfigBase.SlpConfigAction.ExecuteAction(String actionId)
(01) 2018-07-23 09:32:14 Slp:         at Microsoft.SqlServer.Configuration.SqlConfigBase.SlpConfigAction.Execute(String actionId, TextWriter errorStream)
(01) 2018-07-23 09:32:14 Slp: Watson Bucket 1 
 Original Parameter Values 

看了几个错误日志,总之就是围绕启动服务出错。干脆启动SQL Server单机模式碰碰运气。在cmd里输入:

sqlservr.exe -m

运行后,错误提示:"The application was unable to start correctly (0xc0000142)"。还是没有得到进一步的进展,我决定运行Procmon分别抓取正常机器和这台错误机器的执行信息,发现区别就在于错误的机器在读取sqltses.ini后便退出了进程。在这之前werfault相关的操作也进入视野,决定用WinDbg看一下相关的hdmp文件。运行WinDbg并输入:

!analyze -v
*******************************************************************************
*                                                                             *
*                        Exception Analysis                                   *
*                                                                             *
*******************************************************************************

Unable to load image C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Binn\sqldk.dll, Win32 error 0n2
*** WARNING: Unable to verify timestamp for sqldk.dll
GetUrlPageData2 (WinHttp) failed: 12002.

KEY_VALUES_STRING: 1


STACKHASH_ANALYSIS: 1

TIMELINE_ANALYSIS: 1

Timeline: !analyze.Start
    Name: <blank>
    Time: 2018-07-23T06:27:15.719Z
    Diff: 3227719 mSec

Timeline: Dump.Current
    Name: <blank>
    Time: 2018-07-23T05:33:28.0Z
    Diff: 0 mSec

Timeline: Process.Start
    Name: <blank>
    Time: 2018-07-23T05:33:27.0Z
    Diff: 1000 mSec

Timeline: OS.Boot
    Name: <blank>
    Time: 2018-07-23T02:45:30.0Z
    Diff: 10078000 mSec


DUMP_CLASS: 2

DUMP_QUALIFIER: 400

CONTEXT:  (.ecxr)
rax=0000000000000000 rbx=00000000000000c4 rcx=00000000ffffffff
rdx=0000000000000000 rsi=000000000000009d rdi=000007faeafbce48
rip=000007fb0bd831f3 rsp=0000001803fef100 rbp=0000000000000000
 r8=0000000000000000  r9=0000000000000000 r10=0000000000000000
r11=000007faeb398310 r12=000007faeab52ab0 r13=0000000000000000
r14=000007faeab50000 r15=0000000000000000
iopl=0         nv up ei pl zr na po nc
cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010246
msvcr120!log10+0x313:
000007fb`0bd831f3 c5e173d034      vpsrlq  xmm3,xmm0,34h
Resetting default scope

FAULTING_IP: 
msvcr120!log10+313 [f:\dd\vctools\crt\fpw32\tran\amd64\log10.asm @ 420]
000007fb`0bd831f3 c5e173d034      vpsrlq  xmm3,xmm0,34h

EXCEPTION_RECORD:  (.exr -1)
ExceptionAddress: 000007fb0bd831f3 (msvcr120!log10+0x0000000000000313)
   ExceptionCode: c000001d (Illegal instruction)
  ExceptionFlags: 00000000
NumberParameters: 0

DEFAULT_BUCKET_ID:  ILLEGAL_INSTRUCTION

ERROR_CODE: (NTSTATUS) 0xc000001d - {EXCEPTION}  Illegal Instruction  An attempt was made to execute an illegal instruction.

EXCEPTION_CODE: (NTSTATUS) 0xc000001d - {EXCEPTION}  Illegal Instruction  An attempt was made to execute an illegal instruction.

EXCEPTION_CODE_STR:  c000001d

WATSON_BKT_PROCSTAMP:  5724ae45

WATSON_BKT_PROCVER:  2015.130.1601.5

WATSON_BKT_MODULE:  msvcr120.dll

WATSON_BKT_MODSTAMP:  56bc00d3

WATSON_BKT_MODOFFSET:  931f3

WATSON_BKT_MODVER:  12.0.40649.5

MODULE_VER_PRODUCT:  Microsoft? Visual Studio? 2013

BUILD_VERSION_STRING:  6.2.9200.16384 (win8_rtm.120725-1247)

MODLIST_WITH_TSCHKSUM_HASH:  c6a5860b5b55160212c48b9276e6eba3de41b840

MODLIST_SHA1_HASH:  8ff0cba4b013ab435c80aab51efa92ac767733be

NTGLOBALFLAG:  0

PROCESS_BAM_CURRENT_THROTTLED: 0

PROCESS_BAM_PREVIOUS_THROTTLED: 0

APPLICATION_VERIFIER_FLAGS:  0

PRODUCT_TYPE:  3

SUITE_MASK:  400

DUMP_FLAGS:  d96

DUMP_TYPE:  0

PROCESS_NAME:  unknown

ANALYSIS_SESSION_HOST:  JUNCHU-XPS

ANALYSIS_SESSION_TIME:  07-23-2018 14:27:15.0719

ANALYSIS_VERSION: 10.0.17712.1000 amd64fre

THREAD_ATTRIBUTES: 
OS_LOCALE:  ENU

BUGCHECK_STR:  ILLEGAL_INSTRUCTION

PRIMARY_PROBLEM_CLASS:  ILLEGAL_INSTRUCTION

PROBLEM_CLASSES: 

    ID:     [0n321]
    Type:   [@APPLICATION_FAULT_STRING]
    Class:  Primary
    Scope:  DEFAULT_BUCKET_ID (Failure Bucket ID prefix)
            BUCKET_ID
    Name:   Omit
    Data:   Add
            String: [ILLEGAL_INSTRUCTION]
    PID:    [Unspecified]
    TID:    [Unspecified]
    Frame:  [0]

LAST_CONTROL_TRANSFER:  from 000007faeabdb342 to 000007fb0bd831f3

STACK_TEXT:  
00000018`03fef100 000007fa`eabdb342 : 00000000`000000dd 000007fa`ea7e2679 00003862`7c0b2ebe 000007fb`1906c113 : msvcr120!log10+0x313
00000018`03fef160 000007fb`0bd1276b : 00000000`000000c4 00000000`00000000 00000000`0000009d 000007fb`1905a57e : sqltses!InitializeRoundArrays+0x42
00000018`03fef250 000007fa`eab869d6 : 00000000`00000000 00000018`03fef8d0 00000018`03fef8d0 000007fa`ea698920 : msvcr120!_initterm+0x3f
00000018`03fef280 000007fa`eab52b72 : 00000000`00000001 00000018`03fef670 00000000`00000001 000007fa`eab52ab0 : sqltses!CRT_INIT+0x1df
00000018`03fef2c0 000007fb`1905b9be : 000007fa`eab50000 00000018`03fef8d0 00000000`00000001 00000018`041551e0 : sqltses!DllMainCRTStartup+0xb6
00000018`03fef300 000007fb`1907b3fc : 00000018`04154f10 000007fa`eab50000 00000018`04154e90 00000018`04154df0 : ntdll!LdrpCallInitRoutine+0x3e
00000018`03fef350 000007fb`1907a88b : 00000018`04154f10 00000018`04154f01 00000018`03fef400 000007fb`190c9dd0 : ntdll!LdrpInitializeNode+0x192
00000018`03fef450 000007fb`1907e74e : 00000018`04154400 00000018`04154700 00000018`03fef4d0 000007fb`1906aa52 : ntdll!LdrpInitializeGraph+0x6f
00000018`03fef490 000007fb`1907e74e : 00000000`00000000 00000018`041523b0 00000018`03fef510 00000000`00000003 : ntdll!LdrpInitializeGraph+0x8d
00000018`03fef4d0 000007fb`19082858 : 00000000`00000000 00000000`00000000 00000018`03fef550 00000000`00000001 : ntdll!LdrpInitializeGraph+0x8d
00000018`03fef510 000007fb`19081826 : 00000018`03fef8d0 000007fb`19083ce3 00000000`00000000 000007f7`7d8b8000 : ntdll!LdrpInitializeProcess+0x1a1b
00000018`03fef810 000007fb`1906c1ae : 00000018`03fef8d0 00000000`00000000 000007f7`7d8b8000 00000000`00000000 : ntdll!_LdrpInitialize+0x1565e
00000018`03fef880 00000000`00000000 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : ntdll!LdrInitializeThunk+0xe


FAILED_INSTRUCTION_ADDRESS: 
msvcr120!log10+313 [f:\dd\vctools\crt\fpw32\tran\amd64\log10.asm @ 420]
000007fb`0bd831f3 c5e173d034      vpsrlq  xmm3,xmm0,34h

THREAD_SHA1_HASH_MOD_FUNC:  4bb6d88aecf5843ccdb8c6a0528c256becdc603e

THREAD_SHA1_HASH_MOD_FUNC_OFFSET:  1732d2863928a4e53da11554f7406e3cc67c47dd

THREAD_SHA1_HASH_MOD:  b5fd421a131c6f1c77c4a87353281934f433e4d5

FOLLOWUP_IP: 
msvcr120!log10+313 [f:\dd\vctools\crt\fpw32\tran\amd64\log10.asm @ 420]
000007fb`0bd831f3 c5e173d034      vpsrlq  xmm3,xmm0,34h

FAULT_INSTR_CODE:  d073e1c5

FAULTING_SOURCE_LINE:  f:\dd\vctools\crt\fpw32\tran\amd64\log10.asm

FAULTING_SOURCE_FILE:  f:\dd\vctools\crt\fpw32\tran\amd64\log10.asm

FAULTING_SOURCE_LINE_NUMBER:  420

FAULTING_SOURCE_CODE:  
No source found for ''f:\dd\vctools\crt\fpw32\tran\amd64\log10.asm''


SYMBOL_STACK_INDEX:  0

SYMBOL_NAME:  msvcr120!log10+313

FOLLOWUP_NAME:  MachineOwner

MODULE_NAME: msvcr120

IMAGE_NAME:  msvcr120.dll

DEBUG_FLR_IMAGE_TIMESTAMP:  56bc00d3

STACK_COMMAND:  dt ntdll!LdrpLastDllInitializer BaseDllName ; dt ntdll!LdrpFailureData ; ~0s ; .ecxr ; kb

FAILURE_BUCKET_ID:  ILLEGAL_INSTRUCTION_c000001d_msvcr120.dll!log10

BUCKET_ID:  ILLEGAL_INSTRUCTION_BAD_IP_msvcr120!log10+313

FAILURE_EXCEPTION_CODE:  c000001d

FAILURE_IMAGE_NAME:  msvcr120.dll

BUCKET_ID_IMAGE_STR:  msvcr120.dll

FAILURE_MODULE_NAME:  msvcr120

BUCKET_ID_MODULE_STR:  msvcr120

FAILURE_FUNCTION_NAME:  log10

BUCKET_ID_FUNCTION_STR:  log10

BUCKET_ID_OFFSET:  313

BUCKET_ID_MODTIMEDATESTAMP:  56bc00d3

BUCKET_ID_MODCHECKSUM:  f6c2b

BUCKET_ID_MODVER_STR:  12.0.40649.5

BUCKET_ID_PREFIX_STR:  ILLEGAL_INSTRUCTION_BAD_IP_

FAILURE_PROBLEM_CLASS:  ILLEGAL_INSTRUCTION

FAILURE_SYMBOL_NAME:  msvcr120.dll!log10

WATSON_STAGEONE_URL:  http://watson.microsoft.com/StageOne/unknown/2015.130.1601.5/5724ae45/msvcr120.dll/12.0.40649.5/56bc00d3/c000001d/000931f3.htm?Retriage=1

TARGET_TIME:  2018-07-23T05:33:28.000Z

OSBUILD:  9200

OSSERVICEPACK:  16384

SERVICEPACK_NUMBER: 0

OS_REVISION: 0

OSPLATFORM_TYPE:  x64

OSNAME:  Windows 8

OSEDITION:  Windows 8 Server TerminalServer DataCenter SingleUserTS

USER_LCID:  0

OSBUILD_TIMESTAMP:  2012-07-26 10:15:22

BUILDDATESTAMP_STR:  120725-1247

BUILDLAB_STR:  win8_rtm

BUILDOSVER_STR:  6.2.9200.16384

ANALYSIS_SESSION_ELAPSED_TIME:  591b

ANALYSIS_SOURCE:  UM

FAILURE_ID_HASH_STRING:  um:illegal_instruction_c000001d_msvcr120.dll!log10

FAILURE_ID_HASH:  {5866d3bb-feda-328f-6d8f-83f8512752ce}

Followup:     MachineOwner
---------

初步看了一下是调用msvcr120!log10出现了错误并提示“illegal instruction”,原来是VC 2013的错误,log10应该是数学库提供的函数。于是打开必应输入关键字"vc2013 log10 Illegal Instruction",果然是VC 2013的bug,下载对应更新包安装重启计算机问题解决。

官方地址:FIX: Programs that are built in Visual C++ 2013 crash with "Illegal Instruction" exception

关于SQL Server 2016中的Json函数sql server json 解析的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于java – Sql Server 2016:为SQL Server连接启用TLS 1.2、jMeter ServerAgent在Windows Server 2016中崩溃、jquery – SQL Server中的JSON数据处理、SQL Server 2012 R2升级到SQL Server 2016无法正常启动数据库服务解决方案等相关知识的信息别忘了在本站进行查找喔。

对于如何通过ODBC连接在c#中传递Informix集合参数感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍LIST,SET,MULTISET,并为您提供关于$.ajax () 方法详解 ajax 之 async 属性 【原创】详细案例解剖 —— 浅谈 Redis 缓存的常用 5 种方式(String,Hash,List,set,SetSorted )、Android List,Set,Map集合安全 集合区别 并发集合类性能分析、C++ multiset,STL multiset详解、C++/STL关联容器-集合-multiset&set的用法的有用信息。

本文目录一览:

如何通过ODBC连接在c#中传递Informix集合参数(LIST,SET,MULTISET)

如何通过ODBC连接在c#中传递Informix集合参数(LIST,SET,MULTISET)

我正在寻找一种在C#中传递Informix列表参数的方法。

我问过一个关于如何将多值参数传递给Informix的问题,但是现在我需要从C#中执行它。

在简历中,我有一个这样的程序。

CREATE PROCEDURE test_3(c LIST(CHAR(10) NOT NULL))    RETURNING CHAR(10) AS r;    DEFINE r CHAR(10);    FOREACH SELECT * INTO r FROM TABLE(c)        RETURN r WITH RESUME;    END FOREACH;END PROCEDURE;

像这样在Aqua Data Studio.8.0.22中执行它可以正常工作

 EXECUTE PROCEDURE test_3(''LIST{''''stspols'''',''''stsrepo''''}'');

因此,我举了一个简短的示例说明如何在c#中执行它。

首先像 CommandType.Text

string strParameters = "LIST{''''stspols'''',''''stsrepo''''}";using (OdbcConnection oConnection = new OdbcConnection("DSN=MYDSN;UID=MYUID;PWD=MYPWD;"))      {           oConnection.Open();           using (OdbcDataAdapter oCommand = new OdbcDataAdapter(string.Format("EXECUTE PROCEDURE test_3(''{0}'')", strParameters), oConnection))           {                                   using (DataTable dt = new DataTable())                {                            oCommand.Fill(dt);                }            }      }

这个作品很好。

所以我很好奇并试图执行它,但是 CommandType.StoredProcedure

string strParameters = "LIST{''''stspols'''',''''stsrepo''''}";            using (OdbcConnection oConnection = new OdbcConnection("DSN=MYDSN;UID=MYUID;PWD=MYPWD;"))            {                oConnection.Open();                using (OdbcCommand oCommand = new OdbcCommand("{CALL test_3(?)}", oConnection))                {                    oCommand.CommandType = CommandType.StoredProcedure;                    OdbcParameter oParameter = new OdbcParameter("c", OdbcType.Char, 4000);                    oParameter.Value = strParameters;                    oCommand.Parameters.Add(oParameter);                    using (OdbcDataAdapter oDataAdapter = new OdbcDataAdapter(oCommand))                    {                        using (DataTable dt = new DataTable())                        {                            oDataAdapter.Fill(dt);                        }                    }                }            }

但是现在我明白了 ERROR [HY000] [Informix][Informix ODBC Driver][Informix]Invalidcollection literal value.

所以所有这些之后,我的最后一个问题是

我如何从C#中使用Collection参数类型(LIST,SET,MULTISET)作为存储过程来执行这种Informix过程。

显然我做错了。

在此先感谢您的宝贵帮助。

答案1

在原始SQL中,加倍的单引号是必需的,但在参数化查询中则不需要。您应该能够替换:

string strParameters = "LIST{''''stspols'''',''''stsrepo''''}";

和:

string strParameters = "LIST{''stspols'',''stsrepo''}";

了解何时需要将引号加倍,何时不应该加倍,但“不在占位符值中”是准确的。

$.ajax () 方法详解 ajax 之 async 属性 【原创】详细案例解剖 —— 浅谈 Redis 缓存的常用 5 种方式(String,Hash,List,set,SetSorted )

$.ajax () 方法详解 ajax 之 async 属性 【原创】详细案例解剖 —— 浅谈 Redis 缓存的常用 5 种方式(String,Hash,List,set,SetSorted )

$.ajax () 方法详解

 

jquery 中的 ajax 方法参数总是记不住,这里记录一下。

 

1.url
要求为 String 类型的参数,(默认为当前页地址)发送请求的地址。

2.type
要求为 String 类型的参数,请求方式(post 或 get)默认为 get。注意其他 http 请求方法,例如 put 和 delete 也可以使用,但仅部分浏览器支持。

3.timeout
要求为 Number 类型的参数,设置请求超时时间(毫秒)。此设置将覆盖 $.ajaxSetup () 方法的全局设置。

4.async
要求为 Boolean 类型的参数,默认设置为 true,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。注意,同步请求将锁住浏览器,用户其他操作必须等待请求完成才可以执行。

5.cache
要求为 Boolean 类型的参数,默认为 true(当 dataType 为 script 时,默认为 false),设置为 false 将不会从浏览器缓存中加载请求信息。

6.data
要求为 Object 或 String 类型的参数,发送到服务器的数据。如果已经不是字符串,将自动转换为字符串格式。get 请求中将附加在 url 后。防止这种自动转换,可以查看  processData 选项。对象必须为 key/value 格式,例如 {foo1:"bar1",foo2:"bar2"} 转换为 & foo1=bar1&foo2=bar2。如果是数组,JQuery 将自动为不同值对应同一个名称。例如 {foo:["bar1","bar2"]} 转换为 & foo=bar1&foo=bar2。

7.dataType
要求为 String 类型的参数,预期服务器返回的数据类型。如果不指定,JQuery 将自动根据 http 包 mime 信息返回 responseXML 或 responseText,并作为回调函数参数传递。可用的类型如下:
xml:返回 XML 文档,可用 JQuery 处理。
html:返回纯文本 HTML 信息;包含的 script 标签会在插入 DOM 时执行。
script:返回纯文本 JavaScript 代码。不会自动缓存结果。除非设置了 cache 参数。注意在远程请求时(不在同一个域下),所有 post 请求都将转为 get 请求。
json:返回 JSON 数据。
jsonp:JSONP 格式。使用 SONP 形式调用函数时,例如 myurl?callback=?,JQuery 将自动替换后一个 “?” 为正确的函数名,以执行回调函数。
text:返回纯文本字符串。

8.beforeSend
要求为 Function 类型的参数,发送请求前可以修改 XMLHttpRequest 对象的函数,例如添加自定义 HTTP 头。在 beforeSend 中如果返回 false 可以取消本次 ajax 请求。XMLHttpRequest 对象是惟一的参数。
            function(XMLHttpRequest){
               this;   // 调用本次 ajax 请求时传递的 options 参数
            }
9.complete
要求为 Function 类型的参数,请求完成后调用的回调函数(请求成功或失败时均调用)。参数:XMLHttpRequest 对象和一个描述成功请求类型的字符串。
          function(XMLHttpRequest, textStatus){
             this;    // 调用本次 ajax 请求时传递的 options 参数
          }

10.success:要求为 Function 类型的参数,请求成功后调用的回调函数,有两个参数。
         (1) 由服务器返回,并根据 dataType 参数进行处理后的数据。
         (2) 描述状态的字符串。
         function(data, textStatus){
            //data 可能是 xmlDoc、jsonObj、html、text 等等
            this;  // 调用本次 ajax 请求时传递的 options 参数
         }

11.error:
要求为 Function 类型的参数,请求失败时被调用的函数。该函数有 3 个参数,即 XMLHttpRequest 对象、错误信息、捕获的错误对象 (可选)。ajax 事件函数如下:
       function(XMLHttpRequest, textStatus, errorThrown){
          // 通常情况下 textStatus 和 errorThrown 只有其中一个包含信息
          this;   // 调用本次 ajax 请求时传递的 options 参数
       }

12.contentType
要求为 String 类型的参数,当发送信息至服务器时,内容编码类型默认为 "application/x-www-form-urlencoded"。该默认值适合大多数应用场合。

13.dataFilter
要求为 Function 类型的参数,给 Ajax 返回的原始数据进行预处理的函数。提供 data 和 type 两个参数。data 是 Ajax 返回的原始数据,type 是调用 jQuery.ajax 时提供的 dataType 参数。函数返回的值将由 jQuery 进一步处理。
            function(data, type){
                // 返回处理后的数据
                return data;
            }

14.dataFilter
要求为 Function 类型的参数,给 Ajax 返回的原始数据进行预处理的函数。提供 data 和 type 两个参数。data 是 Ajax 返回的原始数据,type 是调用 jQuery.ajax 时提供的 dataType 参数。函数返回的值将由 jQuery 进一步处理。
            function(data, type){
                // 返回处理后的数据
                return data;
            }

15.global
要求为 Boolean 类型的参数,默认为 true。表示是否触发全局 ajax 事件。设置为 false 将不会触发全局 ajax 事件,ajaxStart 或 ajaxStop 可用于控制各种 ajax 事件。

16.ifModified
要求为 Boolean 类型的参数,默认为 false。仅在服务器数据改变时获取新数据。服务器数据改变判断的依据是 Last-Modified 头信息。默认值是 false,即忽略头信息。

17.jsonp
要求为 String 类型的参数,在一个 jsonp 请求中重写回调函数的名字。该值用来替代在 "callback=?" 这种 GET 或 POST 请求中 URL 参数里的 "callback" 部分,例如 {jsonp:''onJsonPLoad''} 会导致将 "onJsonPLoad=?" 传给服务器。

18.username
要求为 String 类型的参数,用于响应 HTTP 访问认证请求的用户名。

19.password
要求为 String 类型的参数,用于响应 HTTP 访问认证请求的密码。

20.processData
要求为 Boolean 类型的参数,默认为 true。默认情况下,发送的数据将被转换为对象(从技术角度来讲并非字符串)以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或者其他不希望转换的信息,请设置为 false。

21.scriptCharset
要求为 String 类型的参数,只有当请求时 dataType 为 "jsonp" 或者 "script",并且 type 是 GET 时才会用于强制修改字符集 (charset)。通常在本地和远程的内容编码不同时使用。

案例代码:

复制代码
$(function(){
    $(''#send'').click(function(){
         $.ajax({
             type: "GET",
             url: "test.json",
             data: {username:$("#username").val(), content:$("#content").val()},
             dataType: "json",
             success: function(data){
                         $(''#resText'').empty();   //清空resText里面的所有内容
                         var html = ''''; 
                         $.each(data, function(commentIndex, comment){
                               html += ''<div><h6>'' + comment[''username'']
                                         + '':</h6><p'' + comment[''content'']
                                         + ''</p></div>'';
                         });
                         $(''#resText'').html(html);
                      }
         });
    });
});
复制代码

 

22. 顺便说一下 $.each () 函数:
$.each () 函数不同于 JQuery 对象的 each () 方法,它是一个全局函数,不操作 JQuery 对象,而是以一个数组或者对象作为第 1 个参数,以一个回调函数作为第 2 个参数。回调函数拥有两个参数:第 1 个为对象的成员或数组的索引,第 2 个为对应变量或内容。

 

 

ajax 之 async 属性

 

Ajax 请求中的 async:false/true 的作用

官方的解释是:http://api.jquery.com/jQuery.ajax/

async Boolean Default: true 

By default, all requests are sent asynchronous (e.g. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

async. 默认是 true,即为异步方式,$.Ajax 执行后,会继续执行 ajax 后面的脚本,直到服务器端返回数据后,触发 $.Ajax 里的 success 方法,这时候执行的是两个线程。若要将其设置为 false,则所有的请求均为同步请求,在没有返回值之前,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。

下面查看一个示例:

复制代码
1 var temp;
 2 $.ajax({
 3 
 4    async: false,
 5    type : "POST",
 6    url : defaultPostData.url,
 7    dataType : ''json'',
 8    success : function(data) 
 9    {
10 
11       temp=data;
12    }
13 
14 });
15 
16 alert(temp);
复制代码

 

这个 ajax 请求为同步请求,在没有返回值之前,alert (temp) 是不会执行的。

如果 async 设置为:true,则不会等待 ajax 请求返回的结果,会直接执行 ajax 后面的语句。

不过上面设置同步请求的方法,有网友曾经反馈将 async 设成 false 后,原意是想返回数据了再执行 $.Ajax 后面的脚本,没想到这个地方却导致了在火狐浏览器下出现闪屏 (Firefox 11.0),滚动条下拉到底部触发 ajax 的情况。最后只能将 async:false 注释掉, 也就是 async 为 ture 的情况下,成功解决了火狐浏览器滚动条下拉到底部触发 ajax 出现闪屏的问题。

 

【原创】详细案例解剖 —— 浅谈 Redis 缓存的常用 5 种方式(String,Hash,List,set,SetSorted )

 

很多小伙伴没接触过 Redis,以至于去学习的时候感觉云里雾里的,就有一种:教程随你出,懂了算我输的感觉。

每次听圈内人在谈论的时候总是插不上话,小编就偷偷去了解了一下,也算是初入门径。

然后就整理了一下,很简单的一个 demo(小编用的是 C# 语法进行 demo 编写),我们一起来解剖一下。

总共分为两步:

    1、安装 Redis 服务器(其实就是一个 CMD 黑窗窗)。

    2、编写代码(引入动态链接库、编写 5 种常用存储数据类型)

1、安装 Redis 服务器(Windows 系统)

1)、我们先去微软官网下载一个 Redis GitHub:https://github.com/MSOpenTech/redis/releases,然后选择你喜欢的版本 zip 或 msi 下载。

小编下载了一个放在百度云:https://pan.baidu.com/s/1M7ztZvOmR0YPehbRujkM6Q,提取码:uqmw

下载好了后在 C 盘建立一个 redis 文件夹,解压到 redis。

相关程序说明:

    redis.windows.conf 是 redis 的配置文件。

    redis-server.exe 服务器端。

    redis-cli 命令行客户端。

    redis-benchmark:Redis 性能测试工具,测试 Redis 在你的系统及你的配置下的读写性能。

2)、启动服务

Windows+R 输入 cmd 运行,进入我们解压文件的目录(按回车):

cd C:\redis\Redis-x64-3.0.504

 

进入 redis 目录后,在命令行输入如下命令后回车:

redis-server  redis.windows.conf

也可以该命令保存为文件 startup.bat,保存在根目录下,下次就可以直接运行 startup.bat 启动,

 

 

 到这里我们服务器就安装完成了,接下来我们进行测试,看是否能用(是否安装成功)

3)、测试

另外开启一个命令行窗口 进入 redis 目录下 (注意修改自己的 ip(通过 ipconfig 来查看自己本地的 ip 地址)),第一个命令窗口不要关。

cd C:\redis\Redis-x64-3.0.504

运行如下命令:后面添加 --raw,在输出中文时可避免出现乱码,Ip 是你自己本地的 ip

redis-cli.exe -h 192.168.0.43 -p 6379 --raw

写入 redis 缓存,输入如下代码回车,注意写入的值这里不能有空格,也就是或 HelloWorld 是一个字符串。

set keyStr HelloWorld

读入 redis 缓存,输入如下代码回车

get keyStr

 

到这里我们 redis 服务器就安装好了,接下来我们写代码测试(记住,命令窗口(黑窗窗)不能关闭,一旦关闭 redis 就关闭了)

2、编写代码(我们使用 C# 语法进行编写)

我先新建一个控制台应用程序:RedisApplication

然后引入三个动态链接库到项目里面,百度网盘下载链接如下:https://pan.baidu.com/s/1xySWqoootlF9la0NJQSVYg,提取码:qlyx

新建一个学生类:Student

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RedisApplication
{
    public class Student
    {
        public string id { get; set; }
        public string name { get; set; }
    }
}
复制代码

在 Program.cs 编写 redis 缓存与读取,五种方法均在里面,运行时注意吧不测试的注释掉

复制代码
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RedisApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            //在Redis中存储常用的5种数据类型:string,Hash,List,SetSorted ,set
            /// string
            /// Hash
            /// List
            /// SetSorted
            /// set

            RedisClient client = new RedisClient("192.168.0.43", 6379);  //链接Redis服务器
            client.FlushAll();  //命令用于清空整个Redis服务器的数据(删除所有数据库的所有密钥)。

            #region string
            client.Add<string>("StringValueTime", "我已设置过期时间噢30秒后会消失", DateTime.Now.AddMilliseconds(30000));
            while (true)
            {
                if (client.ContainsKey("StringValueTime"))
                {
                    Console.WriteLine("String.键:StringValue,值:{0} {1}", client.Get<string>("StringValueTime"), DateTime.Now);
                    Thread.Sleep(10000);
                }
                else
                {
                    Console.WriteLine("键:StringValue,值:我已过期 {0}", DateTime.Now);
                    break;
                }
            }

            client.Add<string>("StringValue", " String和Memcached操作方法差不多");
            Console.WriteLine("数据类型为:String.键:StringValue,值:{0}", client.Get<string>("StringValue"));

            Student stud = new Student() { id = "1001", name = "李四" };
            client.Add<Student>("StringEntity", stud);
            Student Get_stud = client.Get<Student>("StringEntity");
            Console.WriteLine("数据类型为:String.键:StringEntity,值:{0} {1}", Get_stud.id, Get_stud.name);
            #endregion

            #region Hash
            client.SetEntryInHash("HashID", "Name", "张三");
            client.SetEntryInHash("HashID", "Age", "24");
            client.SetEntryInHash("HashID", "Sex", "男");
            client.SetEntryInHash("HashID", "Address", "上海市XX号XX室");

            List<string> HaskKey = client.GetHashKeys("HashID");
            foreach (string key in HaskKey)
            {
                Console.WriteLine("HashID--Key:{0}", key);
            }

            List<string> HaskValue = client.GetHashValues("HashID");
            foreach (string value in HaskValue)
            {
                Console.WriteLine("HashID--Value:{0}", value);
            }

            List<string> AllKey = client.GetAllKeys(); //获取所有的key。
            foreach (string Key in AllKey)
            {
                Console.WriteLine("AllKey--Key:{0}", Key);
            }
            #endregion

            #region List
            /*
     * list是一个链表结构,主要功能是push,pop,获取一个范围的所有的值等,操作中key理解为链表名字。 
     * Redis的list类型其实就是一个每个子元素都是string类型的双向链表。我们可以通过push,pop操作从链表的头部或者尾部添加删除元素,
     * 这样list既可以作为栈,又可以作为队列。Redis list的实现为一个双向链表,即可以支持反向查找和遍历,更方便操作,不过带来了部分额外的内存开销,
     * Redis内部的很多实现,包括发送缓冲队列等也都是用的这个数据结构 
     */
            client.EnqueueItemOnList("QueueListId", "1.张三");  //入队
            client.EnqueueItemOnList("QueueListId", "2.张四");
            client.EnqueueItemOnList("QueueListId", "3.王五");
            client.EnqueueItemOnList("QueueListId", "4.王麻子");
            int q = client.GetListCount("QueueListId");
            for (int i = 0; i < q; i++)
            {
                Console.WriteLine("QueueListId出队值:{0}", client.DequeueItemFromList("QueueListId"));   //出队(队列先进先出)
            }

            client.PushItemToList("StackListId", "1.张三");  //入栈
            client.PushItemToList("StackListId", "2.张四");
            client.PushItemToList("StackListId", "3.王五");
            client.PushItemToList("StackListId", "4.王麻子");
            int p = client.GetListCount("StackListId");
            for (int i = 0; i < p; i++)
            {
                Console.WriteLine("StackListId出栈值:{0}", client.PopItemFromList("StackListId"));   //出栈(栈先进后出)
            }


            #endregion

            #region Set无序集合
            /*
     它是string类型的无序集合。set是通过hash table实现的,添加,删除和查找,对集合我们可以取并集,交集,差集
     */
            client.AddItemToSet("Set1001", "小A");
            client.AddItemToSet("Set1001", "小B");
            client.AddItemToSet("Set1001", "小C");
            client.AddItemToSet("Set1001", "小D");
            HashSet<string> hastsetA = client.GetAllItemsFromSet("Set1001");
            foreach (string item in hastsetA)
            {
                Console.WriteLine("Set无序集合ValueA:{0}", item); //出来的结果是无须的
            }

            client.AddItemToSet("Set1002", "小K");
            client.AddItemToSet("Set1002", "小C");
            client.AddItemToSet("Set1002", "小A");
            client.AddItemToSet("Set1002", "小J");
            HashSet<string> hastsetB = client.GetAllItemsFromSet("Set1002");
            foreach (string item in hastsetB)
            {
                Console.WriteLine("Set无序集合ValueB:{0}", item); //出来的结果是无须的
            }

            HashSet<string> hashUnion = client.GetUnionFromSets(new string[] { "Set1001", "Set1002" });
            foreach (string item in hashUnion)
            {
                Console.WriteLine("求Set1001和Set1002的并集:{0}", item); //并集
            }

            HashSet<string> hashG = client.GetIntersectFromSets(new string[] { "Set1001", "Set1002" });
            foreach (string item in hashG)
            {
                Console.WriteLine("求Set1001和Set1002的交集:{0}", item);  //交集
            }

            HashSet<string> hashD = client.GetDifferencesFromSet("Set1001", new string[] { "Set1002" });  //[返回存在于第一个集合,但是不存在于其他集合的数据。差集]
            foreach (string item in hashD)
            {
                Console.WriteLine("求Set1001和Set1002的差集:{0}", item);  //差集
            }

            #endregion

            #region  SetSorted 有序集合
            /*
     sorted set 是set的一个升级版本,它在set的基础上增加了一个顺序的属性,这一属性在添加修改.元素的时候可以指定,
     * 每次指定后,zset(表示有序集合)会自动重新按新的值调整顺序。可以理解为有列的表,一列存 value,一列存顺序。操作中key理解为zset的名字.
     */
            client.AddItemToSortedSet("SetSorted1001", "1.刘仔");
            client.AddItemToSortedSet("SetSorted1001", "2.星仔");
            client.AddItemToSortedSet("SetSorted1001", "3.猪仔");
            List<string> listSetSorted = client.GetAllItemsFromSortedSet("SetSorted1001");
            foreach (string item in listSetSorted)
            {
                Console.WriteLine("SetSorted有序集合{0}", item);
            }
            #endregion
        }
    }
}
复制代码

 

如下五种方法:

 

我们运行 Hash 这个方法读取缓存的数据:

 

 很显然,读取成功。

到这里我们的简单 redis 缓存就完成了,是不是很简单,只有理清楚逻辑,一切都好办。

然后小编设想一下,如果我们需要缓存文件,如视频、图片,我们是不是可以先转换为二进制流就行存储读取呢。

这个问题就交给你辣,加油,你可以的。

Android List,Set,Map集合安全 集合区别 并发集合类性能分析

Android List,Set,Map集合安全 集合区别 并发集合类性能分析

对于Android开发者来说深入了解Java的集合类很有必要主要是从Collection和Map接口衍生出来的,目前主要提供了List、Set和 Map这三大类的集合

Collection接口主要有两种子类分别为List和Set,区别主要是List保存的对象可以重复

而Set不可以重复

而Map一般为key-value这样的对应关系,比如我们常用的HashMap。

 

 数组

数组存储区间是连续的,占用内存严重,故空间复杂的很大。但数组的二分查找时间复杂度小,为O(1);数组的特点是:寻址容易,插入和删除困难;

链表

链表存储区间离散,占用内存比较宽松,故空间复杂度很小,但时间复杂度很大,达O(N)。链表的特点是:寻址困难,插入和删除容易。

哈希表

那么我们能不能综合两者的特性,做出一种寻址容易,插入删除也容易的数据结构?答案是肯定的,这就是我们要提起的哈希表。哈希表((Hash table)既满足了数据的查找方便,同时不占用太多的内容空间,使用也十分方便。


 
java中各种集合的关系图 

Collection       接口的接口     对象的集合 
├ List           子接口         按进入先后有序保存   可重复 
│├ LinkedList    接口实现类     链表     插入删除   没有同步   线程不安全 
│├ ArrayList     接口实现类     数组     随机访问   没有同步   线程不安全 
│└ Vector        接口实现类     数组                  同步        线程安全 
│   └ Stack 
└ Set            子接口       仅接收一次,并做内部排序 

├ HashSet 

│   └ LinkedHashSet 
└ TreeSet 
 
List 主要有ArrayList、LinkedList、Vector和Stack 
一、List 主要有ArrayList、LinkedList、Vector和Stack
有关这些子类的性能,Android开发网从插入、删除、移动等方面按照元素的执行效率做一一分析,通过分析Sun 的Java源码和实际元素操作得出下面结论:

        ArrayList -是线程不安全 底层是由数组实现 他的构造主要从AbstractList实现,主要是判断下初始元素的容量,ArrayList最大的特点就是提供了Add、Get操作,当然可以通过迭代器来遍历,对于元素的存在可以通过contains方法判断。

       LinkedList - 线程不安全的 作为一种双向链表结构,对于元素的插入、删除效率比较高,只需要调整节点指向即可,但是对于随机查找而言性能主要看这个链表长度和运气了。 LinkedList也提供了ArrayList的get方法,但是要复杂的多,主要通过next或previous方法遍历得到,LinkedList要移动指针。

       Vector -线程安全的,这两个类底层都是由数组实现的,效率低  比较简单和ArrayList差不多,主要是内部实现了synchronized关键字,实现了线程安全访问但性能有些降低,同时对于元素的扩充在算法上和ArrayList稍有不同,通过构造的容量增量系数来决定。

       Stack - 作为栈的操作,本次继承于Vector,提供了push,pop和peek方法,peek是不弹出根据数据大小获取最后一个元素对象。
 
  二、Set 主要有HashSet 和 TreeSet 

  HashSet - 该类是从Set接口继承而来,相对于List而言就是说内部添加的元素不能重复, Hashtable 继承 Map 接口,实现一个 key-value 映射的哈希表。任何非空( non-null )的对象都可作为 key 或者 value 。 当然从名字的Hash来看就是通过哈希算法来实现防止冲突来获得防止重复的,整体上从HashMap实现,存放元素方法的也是类似key- value的对应的,通过迭代器遍历,不过HashSet不是线程安全的。 

  TreeSet - 这个相对于HashSet而言主要是提供了排序支持,TreeSet是从TreeMap类实现,也是非线程安全的。 

  可以看到Set的两个类都和Map有关,下面就一起看下有关映射(Map)相关的使用。 

 

  三、Map 主要有 HashMap 和 TreeMap 
 
 

HashMap和Hashtable的区别

HashMap和Hashtable都实现了Map接口,但决定用哪一个之前先要弄清楚它们之间的分别。主要的区别有:线程安全性,同步(synchronization),以及速度。

  1. HashMap几乎可以等价于Hashtable,除了HashMap是非synchronized的,并可以接受null(HashMap可以接受为null的键值(key)和值(value),而Hashtable则不行)。
  2. HashMap是非synchronized,而Hashtable是synchronized,这意味着Hashtable是线程安全的,多个线程可以共享一个Hashtable;而如果没有正确的同步的话,多个线程是不能共享HashMap的。Java 5提供了ConcurrentHashMap,它是HashTable的替代,比HashTable的扩展性更好。
  3. 另一个区别是HashMap的迭代器(Iterator)是fail-fast迭代器,而Hashtable的enumerator迭代器不是fail-fast的。所以当有其它线程改变了HashMap的结构(增加或者移除元素),将会抛出ConcurrentModificationException,但迭代器本身的remove()方法移除元素则不会抛出ConcurrentModificationException异常。但这并不是一个一定发生的行为,要看JVM。这条同样也是Enumeration和Iterator的区别。
  4. 由于Hashtable是线程安全的也是synchronized,所以在单线程环境下它比HashMap要慢。如果你不需要同步,只需要单一线程,那么使用HashMap性能要好过Hashtable。
  5. HashMap不能保证随着时间的推移Map中的元素次序是不变的。


  HashMap - ,可以为空,提供了比较强大的功能实现,比如说loadFactor可以控制元素增长时内存分配,HashMap也是非线程安全的。 
 
原理:

C++ multiset,STL multiset详解

C++ multiset,STL multiset详解

multiset 是关联容器的一种,是排序好的集合(元素已经进行了排序),并且允许有相同的元素。

不能直接修改 multiset 容器中元素的值。因为元素被修改后,容器并不会自动重新调整顺序,于是容器的有序性就会被破坏,再在其上进行查找等操作就会得到错误的结果。因此,如果要修改 multiset 容器中某个元素的值,正确的做法是先删除该元素,再插入新元素。

使用 multiset 必须包含头文件 <set>。multiset 类模板的定义如下:

template <class Key,class Pred = less<Key>,class B = allocator<Key> > class multiset {
    ...
};

该模板有三个类型参数:Key、Pred 和 B。类型参数可以有默认值,默认值就是某种类型。例如,Pred 类型参数的默认值就是 less<Key> 类型,B 的默认值就是 allocator<Key> 类型。第三个类型参数极少用到,一般都用默认值,因此这里不做介绍。

第一个类型参数说明 multiset 容器中的每个元素都是 Key 类型的。第二个类型参数 Pred 用于指明容器中元素的排序规则,在被实例化后,Pred 可以是函数对象类,也可以是函数指针类型。

multiset 内部在排序时定义了一个变量Pred op,根据表达式op(x,y)来比较两个元素 x、y 的大小。该表达式的值为 true,则说明 x 比 y 小。Pred 的默认值是 less<Key>,less 是 STL 中的函数对象类模板,其定义如下:
template <class_Tp>
struct less
{
    bool operator() (const _Tp &__x,const _Tp &__y) const
    { return __x < __y; }
};
这说明,在默认情况下,multiset 容器中的元素是用<运算符比较大小的。例如,假设 A 是一个类的名字,可以定义一个如下的容器对象:

multiset <A> s;

由于 multiset 的类型参数可以使用默认值,因此上面的语句等价于:

multiset < int,less<A>,allocator<A> > s;

模板类 multiset < A,allocator<A> > 的 insert 成员函数可以用来插入一个元素。 插入过程中需要进行元素之间的比较,可以认为 insert 成员函数中定义了一个变量 less <A> op,用 op(x,y) 来比较元素 x、y 的大小。归根到底,还是用<运算符比较 x、y 的大小。 因此,<运算符必须经过适当重载,才可以向 multiset <A>容器中插人元素。

下面的程序 会编译出错:
#include <set>
using namespace std;
class A{};
int main(){
    multiset <A> a;
    a.insert( A() );  //编译出错,因为不能用“<”运算符比较两个A对象
}
multiset 常用的成员函数如表 1 所示。有的成员函数有不止一个版本,这里不一一 列出。

表1:multiset 的成员函数
成员函数或成员函数模板 作  用
iterator find (const T & val); 在容器中查找值为 val 的元素,返回其迭代器。如果找不到,返 回 end()
iterator insert( const T & val); 将 val 插入容器中并返回其迭代器
void insert(iterator first,iterator last); 将区间 [first,last) 中的元素插人容器
int count( const T & val); 统计有多少个元素的值和 val 相等
iterator lower_bound( const T & val); 查找一个最大的位置 it,使得 [begin(), it) 中所有的元素者比 val 小
iterator upper_bound( const T & val); 查找一个最小的位置 it,使得 [it, end()) 中所有的元素都比 val 大
pair <iterator,iterator > equal_range (const T & val); 同时求得 lower_bound 和 upper_bound
iterator erase(iterator it); 删除 it 指向的元素,返回其后面的元素的迭代器(Visual Studio 2010 中如此,但是在 C++ 标准和 Dev C++ 中,返回值不是这样)
iterator erase(iterator first,iterator last); 删除区间 [first,last),返回 last(Visual Studio 2010 中如此,但是在 C++ 标准和 Dev C++ 中,返回值不是这样)

multiset 及 set 中的 find 和 count 并不是用==运算符比较元素是否和待查找的值相等的。它们进行比较的原则是:如果x比y小y比x小同时为假,就认为 x 和 y 相等。

下面通过一个例子说明 multiset 的用法。
#include <iostream>
#include <set>  //使用multiset须包含此头文件
using namespace std;
template <class T>
void Print(T first,T last)
{
    for (; first != last; ++first)
        cout << *first << " ";
    cout << endl;
}
class A
{
private:
    int n;
public:
    A(int n_) { n = n_; }
    friend bool operator < (const A & a1,const A & a2)
    { return a1.n < a2.n; }
    friend ostream & operator << (ostream & o,const A & a2)
    { o << a2.n; return o; }
    friend class MyLess;
};
class MyLess
{
public:
    bool operator() (const A & a1,const A & a2)  //按个位数比较大小
    { return (a1.n % 10) < (a2.n % 10); }
};
typedef multiset <A> MSET1;  //MSET1 用“<”运算符比较大小
typedef multiset <A,MyLess> MSET2;  //MSET2 用 MyLess::operator() 比较大小
int main()
{
    const int SIZE = 6;
    A a[SIZE] = { 4,22,19,8,33,40 };
    MSET1 m1;
    m1.insert(a,a + SIZE);
    m1.insert(22);
    cout << "1)" << m1.count(22) << endl;  //输出 1)2
    cout << "2)"; Print(m1.begin(),m1.end());  //输出 2)4 8 19 22 22 33 40
    MSET1::iterator pp = m1.find(19);
    if (pp != m1.end())  //条件为真说明找到
        cout << "found" << endl;  //本行会被执行,输出 found
    cout << "3)"; cout << *m1.lower_bound(22)
        << "," << *m1.upper_bound(22) << endl; //输出 3)22,33
    pp = m1.erase(m1.lower_bound(22),m1.upper_bound(22));
    //pp指向被删元素的下一个元素
    cout << "4)"; Print(m1.begin(),m1.end());  //输出 4)4 8 19 33 40
    cout << "5)"; cout << *pp << endl;  //输出 5)33
    MSET2 m2;  //m2中的元素按n的个位数从小到大排序
    m2.insert(a,a + SIZE);
    cout << "6)"; Print(m2.begin(),m2.end());  //输出 6)40 22 33 4 8 19
    return 0;
}
第 30 行,MSET2 类的排序规则和 MSET1 不同。MSET2 用 MyLess 定义排序规则,即 n 的个位数小的元素排在前面。

第 43、44 行,lower_bound 返回的迭代器指向第一个 22,upper_bound 返回的迭代器指向 33。

第 45 行,删除所有值为 22 的元素。erase 成员函数删除一个元素后,返回下一个元素的迭代器应该是很合理的,但是 C++ 标准委员会认为,返回下一个元素的迭代器也是需要时间开销的,如果程序员不想要这个返回值,那么这个开销就是浪费的——因此在遵循 C++ 标准的 Dev C++ 中,本行无法编译通过。但是微软公司认为应该对这一点做出改进,因此 Visual Studio 2010 将 erase 成员函数处理成返回被删元素下一个元素的迭代器。

不论在哪种编译器中,用 erase 成员函数删除迭代器 i 指向的元素后,迭代器 i 即告失效, 此时不能指望 ++i 后 i 会指向被删除元素的下一个元素;相反,++i 可能立即导致出错。如果想要得到被删除元素后面那个元素的迭代器,可以在删除前获取其迭代器并保存起来(这同样适用于 set、map、multimap 的 erase 成员函数)。事实上,如果得到了某关联容器的迭代器,则该迭代器并不会因为容器中元素的插入以及其他元素的删除而失效。只要该迭代器指向的元素没有被删除,就可以一直使用它。

C++/STL关联容器-集合-multiset&set的用法

C++/STL关联容器-集合-multiset&set的用法

C++ STL set和multiset的使用

std::set<int> s;那个s这个对象里面存贮的元素是从小到大排序的,(因为用std::less作为比较工具。)

1,set的含义是集合,它是一个有序的容器,里面的元素都是排序好的,支持插入,删除,查找等操作,就   像一个集合一样。所有的操作的都是严格在logn时间之内完成,效率非常高。 set和multiset的区别是:set插入的元素不能相同,但是multiset可以相同。

   创建 multiset<ss> base;

   删除:如果删除元素a,那么在定义的比较关系下和a相等的所有元素都会被删除

   base.count( a ):set能返回0或者1,multiset是有多少个返回多少个.

   Set和multiset都是引用<set>头文件,复杂度都是logn

2,Set中的元素可以是任意类型的,但是由于需要排序,所以元素必须有一个序,即大小的比较关系,比如   整数可以用<比较.

3,自定义比较函数;

    include<set>

    typedef struct

    { 定义类型 }

    ss(类型名);

    struct cmp

    {

          bool operator()( const int &a, const int &b ) const

             { 定义比较关系<}

    };

    (运算符重载,重载<)

    set<ss> base; ( 创建一个元素类型是ss,名字是base的set )

    注:定义了<,==和>以及>=,<=就都确定了,STL的比较关系都是用<来确定的,所以必须通    过定义< --“严格弱小于”来确定比较关

4,set的基本操作:

begin()         返回指向第一个元素的迭代器

clear()         清除所有元素

count()         返回某个值元素的个数

empty()         如果集合为空,返回true

end()           返回指向最后一个元素的迭代器

equal_range()   返回集合中与给定值相等的上下限的两个迭代器

erase()         删除集合中的元素

find()          返回一个指向被查找到元素的迭代器

get_allocator() 返回集合的分配器

insert()        在集合中插入元素

lower_bound()   返回指向大于(或等于)某值的第一个元素的迭代器

key_comp()      返回一个用于元素间值比较的函数

max_size()      返回集合能容纳的元素的最大限值

rbegin()        返回指向集合中最后一个元素的反向迭代器

rend()          返回指向集合中第一个元素的反向迭代器

size()          集合中元素的数目

swap()          交换两个集合变量

upper_bound()   返回大于某个值元素的迭代器

value_comp()    返回一个用于比较元素间的值的函数

1:

set元素的插入:

[html]  view plain copy
  1. #include <iostream>  
  2. #include <string>  
  3. #include <set>  
  4. using namespace std;  
  5. void printSet(set<int> s)  
  6. {  
  7.  set<int>::iterator i;  
  8.  for(i=s.begin();i!=s.end();i++)  
  9.         printf("%d ",*i);  
  10.  cout<<endl;  
  11. }  
  12. void main()  
  13. {  
  14.  //创建空的set对象,元素类型为int,  
  15.  set<int> s1;  
  16.  for (int i = 0; i <5 ; i++)  
  17.   s1.insert(i*10);  
  18.  printSet(s1);  
  19.  cout<<"s1.insert(20).second = "<<endl;;  
  20.  if (s1.insert(20).second)//再次插入20     
  21.   cout<<"Insert OK!"<<endl;  
  22.  else  
  23.   cout<<"Insert Failed!"<<endl;  
  24.  cout<<"s1.insert(50).second = "<<endl;  
  25.  if (s1.insert(50).second)  
  26.  {cout<<"Insert OK!"<<endl; printSet(s1);}  
  27.  else  
  28.   cout<<"Insert Failed!"<<endl;  
  29.  pair<set<int>::iterator, bool> p;  
  30.   p = s1.insert(60);  
  31.  if (p.second)  
  32.  {cout<<"Insert OK!"<<endl; printSet(s1);}  
  33.  else  
  34.   cout<<"Insert Failed!"<<endl;  
  35. }  
  36. 继续更新中  

 

2: set 的  empty  erase   删除特定元素

[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <set>  
  3. using namespace std;  
  4. int main ()  
  5. {  
  6.   set<int> myset;  
  7.   myset.insert(20);  
  8.   myset.insert(30);  
  9.   myset.insert(10);  
  10.   while (!myset.empty())  
  11.   {  
  12.      cout <<" "<< *myset.begin();  
  13.      myset.erase(myset.begin());  
  14.   }  
  15.   cout << endl;  
  16.   return 0;  
  17. }  


 

[cpp]  view plain copy
  1. //set::find    
  2. #include <iostream>  
  3. #include <set>  
  4. using namespace std;  
  5.   
  6. int main ()  
  7. {  
  8.   set<int> myset;  
  9.   set<int>::iterator it;  
  10.   for (int i=1; i<=5; i++) myset.insert(i*10);    // set: 10 20 30 40 50  
  11.   it=myset.find(20);  
  12.   myset.erase (it);  
  13.   myset.erase (myset.find(40));  
  14.   myset.erase (30);  
  15.   cout << "myset contains:";  
  16.   for (it=myset.begin(); it!=myset.end(); it++)  
  17.     cout << " " << *it;  
  18.   cout << endl;  
  19.   return 0;  
  20. }  

 lower_bound()返回一个 iterator 它指向在[first,last)标记的有序序列中可以插入value,而不会破坏容器顺序的第一个位置,而这个位置标记了一个大于等于value 的值。  例如,有如下序列:  ia[]={12,15,17,19,20,22,23,26,29,35,40,51};  用值21调用lower_bound(),返回一个指向22的iterator。用值22调用lower_bound(),也返回一个指向22的iterator。

iterator upper_bound( const key_type &key ):返回一个迭代器,指向键值> key的第一个元素。

[cpp]  view plain copy
  1. // 6.set::lower_bound/upper_bound  
  2. #include <iostream>  
  3. #include <set>  
  4. using namespace std;  
  5.   
  6. int main ()  
  7. {  
  8.   set<int> myset;  
  9.   set<int>::iterator it,itlow,itup;  
  10.   
  11.   for (int i=1; i<10; i++) myset.insert(i*10); // 10 20 30 40 50 60 70 80 90  
  12.   
  13.   itlow=myset.lower_bound (30);                //    >=   
  14.   itup=myset.upper_bound (60);                 //     >               
  15.   printf("%d %d",*itlow,*itup);  //  30 70  
  16.   return 0;  
  17. }  


 

[cpp]  view plain copy
  1. // 7.set::equal_elements  
  2. #include <iostream>  
  3. #include <set>  
  4. using namespace std;  
  5.   
  6. int main ()  
  7. {  
  8.   set<int> myset;  
  9.   pair<set<int>::iterator,set<int>::iterator> ret;  
  10.   
  11.   for (int i=1; i<=5; i++) myset.insert(i*10);   // set: 10 20 30 40 50  
  12.   
  13.   ret = myset.equal_range(30);  
  14.   
  15.   cout << "lower bound points to: " << *ret.first << endl;  
  16.   cout << "upper bound points to: " << *ret.second << endl;  
  17.   
  18.   return 0;  
  19. }   
  20.   
  21.   
  22. //lower bound points to: 30  
  23. //upper bound points to: 40  


 set结构体的应用

[cpp]  view plain copy
  1. #include<iostream>  
  2. #include<set>  
  3. using namespace std;  
  4. struct haha  
  5. {     
  6.     int a,b;      
  7.     char s;   
  8.     friend bool operator<(struct haha a,struct haha b)     
  9.     {     
  10.         return a.s<b.s;        
  11.     }     
  12. };  
  13. set<struct haha>element;  
  14. int main()  
  15. {     
  16.     struct haha a,b,c,d,t;    
  17.     a.a=1; a.s='b';   
  18.     b.a=2; b.s='c';   
  19.     c.a=4; c.s='d';   
  20.     d.a=3; d.s='a';  
  21.     element.insert(d);    
  22.     element.insert(b);    
  23.     element.insert(c);    
  24.     element.insert(a);    
  25.     set<struct haha>::iterator it;      
  26.     for(it=element.begin(); it!=element.end();it++)       
  27.         cout<<(*it).a<<" ";   
  28.     cout<<endl;     
  29.     for(it=element.begin(); it!=element.end();it++)       
  30.         cout<<(*it).s<<" ";   
  31. }  


集合的并集 交集  差集 等等 

[cpp]  view plain copy
  1. #include<stdio.h>  
  2. #include<string>  
  3. #include<set>  
  4. #include<iostream>  
  5. #include <algorithm>//包含  
  6. using namespace std;  
  7.   
  8. struct compare//自定义排序方式  
  9. {  
  10.     bool operator ()(string s1,string s2)  
  11.     {  
  12.         return s1>s2;  
  13.     }///自定义一个仿函数  
  14. };  
  15. int main()  
  16. {  
  17.     typedef  set<string,compare>  SET;  
  18.     SET s;//建立第一个集合  
  19.     s.insert(string("sfdsfd"));  
  20.     s.insert(string("apple"));  
  21.     s.insert(string("english"));  
  22.     s.insert(string("dstd"));  
  23.     cout<<"第一个集合s1为:"<<endl;  
  24.      set<string,compare>::iterator it = s.begin();  
  25.     while(it!=s.end())  
  26.         cout<<*it++<<"   ";  
  27.   
  28.     SET s2;//建立第二个集合  
  29.     s2.insert(string("abc"));  
  30.     s2.insert(string("apple"));  
  31.     s2.insert(string("english"));  
  32.     cout<<endl<<"第一个集合s2为:"<<endl;  
  33.     it = s2.begin();  
  34.     while(it!=s2.end())  
  35.         cout<<*it++<<"   ";  
  36.     cout<<endl<<endl;  
  37.       
  38.     string str[10];  
  39.     string *end =set_intersection(s.begin(),s.end(),s2.begin(),s2.end(),str,compare());//求交集,返回值指向str最后一个元素的尾端  
  40.     /*set_intersection包含于#include <algorithm>   头文件中  其中上面的不一定非要为set容器 也可以使数组 但是前提是要把2个数组都排好序才可以 
  41.     返回值是一个指向交集序列末尾的迭代器 至于是什么迭代器与第5个参数有关 如果是数组 返回为int的迭代器 */  
  42.     cout<<"s1,s2的交集为:"<<endl;  
  43.     string *first = str;  
  44.     while(first<end)  
  45.         cout <<*first++<<" ";  
  46.   
  47.   
  48.     cout<<endl<<endl<<"s1,s2的并集为:"<<endl;  
  49.     end =set_union(s.begin(),s.end(),s2.begin(),s2.end(),str,compare());//并集  
  50.     first = str;  
  51.     while(first<end)  
  52.         cout <<*first++<<" ";  
  53.   
  54.   
  55.     cout<<endl<<endl<<"s2相对于s1的差集:"<<endl;   
  56.     first = str;  
  57.     end = std::set_difference(s.begin(),s.end(),s2.begin(),s2.end(),str,compare());//s2相对于s1的差集  
  58.     while(first<end)  
  59.         cout <<*first++<<" ";  
  60.   
  61.   
  62.     cout<<endl<<endl<<"s1相对于s2的差集:"<<endl;   
  63.     first = str;  
  64.     end = std::set_difference(s2.begin(),s2.end(),s.begin(),s.end(),str,compare());//s1相对于s2的差集  
  65.       
  66.     while(first<end)  
  67.         cout <<*first++<<" ";  
  68.     cout<<endl<<endl;  
  69.     first = str;  
  70.     end = std::set_symmetric_difference(s.begin(),s.end(),s2.begin(),s2.end(),str,compare());//上面两个差集的并集  
  71.     while(first<end)  
  72.         cout <<*first++<<" ";  
  73.     cout<<endl;   
  74.   
  75. /* 
  76. set<int>   s3   ;    
  77. set<int>::iterator   iter   =   s3.begin()   ;    
  78. set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end(),inserter(s3,iter));    
  79. copy(s3.begin(),s3.end(),   ostream_iterator<int>(cout,"   ")); 
  80. */  
  81. }  

另外一个实例

[cpp]  view plain copy
  1. /*set_intersection()算法计算两个集合[start1, end1)和[start2, end2)的交集, 交集被储存在result中. 
  2.  
  3. 两个集合以序列的形式给出, 并且必须先按升序排好位置. 
  4.  
  5. set_intersection()的返回值是一个指向交集序列末尾的迭代器. 
  6.  
  7. set_intersection()以线性时间(linear time)运行. 
  8.  
  9. 如果严格弱排序函数对象cmp未指定, set_intersection()将使用<操作符比较元素. 
  10.  
  11. 范例 
  12. */  
  13.   
  14. // set_intersection example  
  15. #include <iostream>  
  16. #include <algorithm>  
  17. #include <vector>  
  18. using namespace std;  
  19.    
  20. int main () {  
  21.   int first[] = {5,10,15,20,25};  
  22.   int second[] = {50,40,30,20,10};  
  23.   vector<int> v(10);                           // 0  0  0  0  0  0  0  0  0  0  
  24.   vector<int>::iterator it;  
  25.    
  26.   sort (first,first+5);     //  5 10 15 20 25  
  27.   sort (second,second+5);   // 10 20 30 40 50  
  28.    
  29.   it=set_intersection (first, first+5, second, second+5, v.begin());  
  30.                                                // 10 20 0  0  0  0  0  0  0  0  
  31.    
  32.   cout << "intersection has " << int(it - v.begin()) << " elements.\n";  
  33.    
  34.   return 0;  
  35. }  
  36. /*输出: intersection has 2 elements*/  






 multiset的删除  重要

a<span style="color: rgb(51, 153, 51);">.</span>erase<span style="color: rgb(0, 153, 0);">(</span>x<span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;//删除集合中所有的x
  • </span><pre class="php geshifilter-php" name="code" style="white-space: pre-wrap; word-wrap: break-word;"><span style="color: rgb(0, 64, 0);">multiset</span><span style="color: rgb(51, 153, 51);"><</span>int<span style="color: rgb(51, 153, 51);">>::</span><span style="color: rgb(0, 64, 0);">iterator</span> it <span style="color: rgb(51, 153, 51);">=</span> a<span style="color: rgb(51, 153, 51);">.</span>find<span style="color: rgb(0, 153, 0);">(</span>x<span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span>
  • <span style="color: rgb(177, 177, 0);">if</span> <span style="color: rgb(0, 153, 0);">(</span>it <span style="color: rgb(51, 153, 51);">!=</span> a<span style="color: rgb(51, 153, 51);">.</span><a target=_blank href="http://www.php.net/end" style="color: rgb(106, 57, 6); text-decoration: none;"><span style="color: rgb(153, 0, 0);">end</span></a><span style="color: rgb(0, 153, 0);">(</span><span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(0, 153, 0);">)</span>
  • <span style="color: rgb(0, 153, 0);">{</span>
  • a<span style="color: rgb(51, 153, 51);">.</span>erase<span style="color: rgb(0, 153, 0);">(</span>it<span style="color: rgb(0, 153, 0);">)</span><span style="color: rgb(51, 153, 51);">;</span> <span style="color: rgb(102, 102, 102);"><em>//这里是删除其中的一个x; 删除的是一个位置 而arase是删除所有位置</em></span>
  • <span style="color: rgb(0, 153, 0);">}</span>

  •  
    

     

     

     

     

     

     

     

     

     

     

     

     

     

     部分参考地址:


    http://www.cnblogs.com/agpro/archive/2010/06/23/1763536.html

     

    关于如何通过ODBC连接在c#中传递Informix集合参数LIST,SET,MULTISET的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于$.ajax () 方法详解 ajax 之 async 属性 【原创】详细案例解剖 —— 浅谈 Redis 缓存的常用 5 种方式(String,Hash,List,set,SetSorted )、Android List,Set,Map集合安全 集合区别 并发集合类性能分析、C++ multiset,STL multiset详解、C++/STL关联容器-集合-multiset&set的用法的相关信息,请在本站寻找。

    如果您对如何在SQL Server 2005中选择最接近的匹配项?感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于如何在SQL Server 2005中选择最接近的匹配项?的详细内容,我们还将为您解答sql查询最接近的数字的相关问题,并且为您提供关于php – 在十进制列中查找MySQL中最接近的匹配项、PHP-MYSQL与多个WHERE最接近的匹配项、php-从数组值组合计算最接近的匹配项、python – 正则表达式,选择最接近的匹配的有价值信息。

    本文目录一览:

    如何在SQL Server 2005中选择最接近的匹配项?(sql查询最接近的数字)

    如何在SQL Server 2005中选择最接近的匹配项?(sql查询最接近的数字)

    在SQL Server
    2005中,我有一个成功销售的输入表,以及各种表,其中包含有关已知客户及其详细信息的信息。对于每一行销售,我需要匹配0或1个已知客户。

    我们从销售表中获得以下信息:
    ServiceId,地址,ZipCode,EmailAddress,HomePhone,FirstName,LastName

    客户信息包括所有这些信息以及“ LastTransaction”日期。

    这些字段中的任何一个都可以映射回0个或多个客户。我们将匹配数视为销售表中的ServiceId,Address +
    ZipCode,EmailAddress或HomePhone完全匹配客户的任何时间。

    问题在于我们掌握了许多客户的信息,有时在同一家庭中有多个客户。这意味着我们可能在同一屋子里有John Doe,Jane Doe,Jim Doe和Bob
    Doe。它们都可以在Address + ZipCode和HomePhone上匹配-并且可能其中一个以上也可以在ServiceId上匹配。

    我需要某种方法来优雅地跟踪交易中客户的“最佳”匹配。如果一个匹配6个字段,而另一个仅匹配5个字段,则该客户应保留为该记录的匹配项。如果有多个匹配项5,而没有一个匹配项,则应保留最近的LastTransaction日期。

    任何想法将不胜感激。

    更新:更清楚一点,我正在寻找一种验证数据行中完全匹配数目的好方法,并根据该信息选择要关联的行。如果姓氏是“
    Doe”,则它必须与客户的姓氏完全匹配,才能算作匹配参数,而不是非常接近的匹配项。

    答案1

    对于SQL Server 2005及更高版本,请尝试:

    ;WITH SalesScore AS (SELECT    s.PK_ID as S_PK        ,c.PK_ID AS c_PK        ,CASE              WHEN c.PK_ID IS NULL THEN 0             ELSE CASE WHEN s.ServiceId=c.ServiceId THEN 1 ELSE 0 END                  +CASE WHEN (s.Address=c.Address AND s.Zip=c.Zip) THEN 1 ELSE 0 END                  +CASE WHEN s.EmailAddress=c.EmailAddress THEN 1 ELSE 0 END                  +CASE WHEN s.HomePhone=c.HomePhone THEN 1 ELSE 0 END         END AS Score    FROM Sales s        LEFT OUTER JOIN Customers c ON s.ServiceId=c.ServiceId                                       OR (s.Address=c.Address AND s.Zip=c.Zip)                                       OR s.EmailAddress=c.EmailAddress                                       OR s.HomePhone=c.HomePhone )SELECT     s.*,c.*    FROM (SELECT              S_PK,MAX(Score) AS Score              FROM SalesScore               GROUP BY S_PK         ) dt        INNER JOIN Sales          s ON dt.s_PK=s.PK_ID         INNER JOIN SalesScore    ss ON dt.s_PK=s.PK_ID AND dt.Score=ss.Score        LEFT OUTER JOIN Customers c ON ss.c_PK=c.PK_ID

    编辑
    我不愿在没有shema的情况下编写太多实际代码,因为我无法实际运行此代码并确保它能正常工作。但是,为了回答如何使用最后交易日期处理关系的问题,这是上述代码的较新版本:

    ;WITH SalesScore AS (SELECT    s.PK_ID as S_PK        ,c.PK_ID AS c_PK        ,CASE              WHEN c.PK_ID IS NULL THEN 0             ELSE CASE WHEN s.ServiceId=c.ServiceId THEN 1 ELSE 0 END                  +CASE WHEN (s.Address=c.Address AND s.Zip=c.Zip) THEN 1 ELSE 0 END                  +CASE WHEN s.EmailAddress=c.EmailAddress THEN 1 ELSE 0 END                  +CASE WHEN s.HomePhone=c.HomePhone THEN 1 ELSE 0 END         END AS Score    FROM Sales s        LEFT OUTER JOIN Customers c ON s.ServiceId=c.ServiceId                                       OR (s.Address=c.Address AND s.Zip=c.Zip)                                       OR s.EmailAddress=c.EmailAddress                                       OR s.HomePhone=c.HomePhone )SELECT    *    FROM (SELECT               s.*,c.*,row_number() over(partition by s.PK_ID order by s.PK_ID ASC,c.LastTransaction DESC) AS RankValue              FROM (SELECT                        S_PK,MAX(Score) AS Score                        FROM SalesScore                         GROUP BY S_PK                   ) dt                  INNER JOIN Sales          s ON dt.s_PK=s.PK_ID                   INNER JOIN SalesScore    ss ON dt.s_PK=s.PK_ID AND dt.Score=ss.Score                  LEFT OUTER JOIN Customers c ON ss.c_PK=c.PK_ID         ) dt2    WHERE dt2.RankValue=1

    php – 在十进制列中查找MySQL中最接近的匹配项

    php – 在十进制列中查找MySQL中最接近的匹配项

    下午,

    我在解决这个问题时遇到了一些困难.我有一个MySQL表,其中列出了英国邮政编码及其经度和纬度值.我希望能够在桌面上进行搜索,找到与给定长/纬度对最接近的邮政编码.

    我一直试图使用的查询是:

    "SELECT id, outcode AS thecode, @la := MATCH(lat) AGAINST(?) AS score_lat, @ln := MATCH(lng) AGAINST(?) AS score_lng, @la + @ln AS score_total FROM postcodes ORDER BY score_total DESC LIMIT 10
    

    然而,这只会返回看似随机的邮政编码,例如使用Lat:55.775549和Long:-4.047556

    Array
    (
    [0] => Array
        (
            [id] => 929
            [thecode] => FK14
            [score_lat] => 0
            [score_lng] => 0
            [score_total] => 0
        )
    
    [1] => Array
        (
            [id] => 2785
            [thecode] => UB3
            [score_lat] => 0
            [score_lng] => 0
            [score_total] => 0
        )
    
    [2] => Array
        (
            [id] => 993
            [thecode] => G70
            [score_lat] => 0
            [score_lng] => 0
            [score_total] => 0
        )
    
    [3] => Array
        (
            [id] => 2849
            [thecode] => WC2B
            [score_lat] => 0
            [score_lng] => 0
            [score_total] => 0
        )
    
    [4] => Array
        (
            [id] => 1057
            [thecode] => GU29
            [score_lat] => 0
            [score_lng] => 0
            [score_total] => 0
        )
    
    [5] => Array
        (
            [id] => 2913
            [thecode] => WS13
            [score_lat] => 0
            [score_lng] => 0
            [score_total] => 0
        )
    
    [6] => Array
        (
            [id] => 1121
            [thecode] => HP20
            [score_lat] => 0
            [score_lng] => 0
            [score_total] => 0
        )
    
    [7] => Array
        (
            [id] => 1185
            [thecode] => IG6
            [score_lat] => 0
            [score_lng] => 0
            [score_total] => 0
        )
    
    [8] => Array
        (
            [id] => 1249
            [thecode] => IV25
            [score_lat] => 0
            [score_lng] => 0
            [score_total] => 0
        )
    
    [9] => Array
        (
            [id] => 1313
            [thecode] => KA8
            [score_lat] => 0
            [score_lng] => 0
            [score_total] => 0
        )
    )
    

    数据库的架构是:

    CREATE TABLE `postcodes` (
      `id` int(11) NOT NULL auto_increment,
      `outcode` varchar(4) NOT NULL,
      `lat` varchar(20) NOT NULL,
      `lng` varchar(20) NOT NULL,
      PRIMARY KEY  (`id`),
      FULLTEXT KEY `lat` (`lat`),
      FULLTEXT KEY `lng` (`lng`)
    ) ENGINE=MyISAM AUTO_INCREMENT=2975 DEFAULT CHARSET=latin1 AUTO_INCREMENT=2975 ;
    

    我希望有人能帮帮忙!如果您需要更多信息,请询问……

    谢谢,

    tip2tail

    解决方法:

    MysqL match()函数用于全文搜索以匹配字符串. (所以它返回零值并不奇怪.)

    如果“最接近”你的意思是你想要计算距离(如’乌鸦飞’那样测量),在地图上的两个点之间,坐标以(十进制度)纬度和经度给出,你真的需要使用大圆距离(GCD)计算.

    http://en.wikipedia.org/wiki/Great-circle_distance

    您可以跳过所有这些血腥的细节,只需使用我的实现.下面是我的一个sql语句的SELECT列表的摘录,这个表达式计算两点之间的距离(以英里为单位)……

         , ACOS(
              COS(radians( d2.latitude ))
            * COS(radians( d1.latitude ))
            * COS(radians( d2.longitude ) - radians( d1.longitude ))
            + SIN(radians( d2.latitude ))
            * SIN(radians( d1.latitude ))
               )*3958.82 AS distance_miles
    

    在此示例中,d1表示原点,d2表示目标点.纬度和经度以DECIMAL值的形式提供.

    对于d1有一个“已知”点,我可以通过这个表达式来排序,以便首先获得“最接近”的d2. (对于多个原点,我可以通过d1.id排序,然后通过这个表达式来获得每个d1最接近的d2.但足够我的问题…

    我从您的问题中复制了查询并对其进行了修改(如下).基本上,我删除了“得分”列,并将其替换为进行距离计算的表达式:

    SELECT id
         , outcode AS thecode
         , ACOS(
               COS(radians( d2.latitude ))
             * COS(radians( @d1_latitude ))
             * COS(radians( d2.longitude ) - radians( @d1_longitude ))
             + SIN(radians( d2.latitude ))
             * SIN(radians( @d1_latitude ))
               )*3958.82 AS distance_miles
      FROM postcodes d2
      JOIN (SELECT @d1_latitude := ?, @d1_longitude := ?) v
     ORDER BY distance_miles LIMIT 10
    

    在这种情况下,@ d1_变量(从绑定变量分配)是“已知”点的纬度和经度.对于postcodes表中的每一行(为方便起见,我将其别名为d2),此表达式计算表中lat / long与“已知”点之间的距离.

    注意:作为v别名的内联视图就在那里,因此您只需将纬度绑定一次,并将值分配给可以引用的用户变量.可以省略该内联视图,您可以看到将纬度绑定两次所需的位置.

    注意:这以“英里”计算距离.您可以通过用不同的值代替3958.82常数来轻松获得以公里(km)为单位的距离.

    注意:没有必要返回距离;你可以把这个表达式放在ORDER BY子句中,如果你只想按距离返回最近的10个,例如

    SELECT id
         , outcode AS thecode
      FROM postcodes d2
      JOIN (SELECT @d1_latitude := ?, @d1_longitude := ?) v
     ORDER
        BY ACOS(
               COS(radians( d2.latitude ))
             * COS(radians( @d1_latitude ))
             * COS(radians( d2.longitude ) - radians( @d1_longitude ))
             + SIN(radians( d2.latitude ))
             * SIN(radians( @d1_latitude ))
               )*3958.82 AS distance_miles
     LIMIT 10
    

    如果你正在寻找两点以外的距离,请告诉我,因为在这种情况下,这个答案对你没有任何帮助.

    PHP-MYSQL与多个WHERE最接近的匹配项

    PHP-MYSQL与多个WHERE最接近的匹配项

    在我的数据库中,我有一个包含产品的表,另一个表具有与每个产品相关的标签.

    当用户查看产品页面时,我想显示与他正在查看的产品“最相关”(或最接近)的产品.

    假设产品带有5种不同的标签.我想获得具有相同5个标记的产品,然后具有相同5个标记的4个产品,然后具有相同5个标记的3个产品,等等…

    为此,我猜测我将不得不创建一个或多个MYSQL查询,但我什至不知道从哪里开始.

    匹配相同的5个标签很容易,我可以只使用WHERE tag =’?’ AND tag =’?’…但是如何获得另一个(4 / 5、3 / 5、2 / 5、1 / 5)?

    任何帮助将不胜感激!

    干杯
    史蒂文

    编辑

    @Orbits:我的标签全都在不同的行上……如果没有,我可能会进行文本匹配,但是确实如此.标签行由(id,tag,product_id)组成

    @ cusimar9:不同的表,如帖子中所述:P

    @vbence:我相信它尽可能简单..这是…但是我没有连接表

    产品:

    CREATE TABLE `products` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
      ...
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
    

    标签:

    CREATE TABLE `tags` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `type` varchar(70) NOT NULL,
      `product_id` int(11) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=116 ;
    

    解决方法:

    字符串文字’Tag1’等当然必须替换为您的标签.

    SELECT products.id, COUNT(tags.id) AS match_level
    FROM products
        LEFT JOIN tags ON tags.product_id = product.id
    WHERE tags.type IN ('Tag1', 'Tag2', 'Tag3', 'Tag4', 'Tag5')
    GROUP BY products.id
    ORDER BY match_level DESC
    

    如果您还没有这样的索引,请将其添加到标签表中.没有索引,您将浪费资源.重要时刻.

    CREATE INDEX multimatch ON tags (type, product_id);
    

    php-从数组值组合计算最接近的匹配项

    php-从数组值组合计算最接近的匹配项

    我有一个零件长度数组,例如:

    array(150, 180, 270);
    

    然后我有一个测量值($a = 440)

    我需要计算长度大于$a的两个最接近的可能组合,而无需手动编写数百种可能的组合来计算出来.

    所以:

    150
    180
    270

    150150
    150180
    150270

    180 180
    180270

    270270

    150150150
    150150180

    ..等等.

    这将需要运行一定的次数,而不仅仅是找到前两个匹配项并停止运行,因为150 150 150比$270 270更接近$a,但可能随后运行.

    编辑:我还需要存储组成匹配的部分的组合,最好存储在数组中.

    我希望我已经解释得足够好,以至于有人可以理解.

    解决方法:

    由于这是一个占用大量资源的脚本,所以我认为最好是预先提供选项以生成选择,然后使用该数据创建变量/对象/ sql脚本以永久存储数据.例如,做类似的事情

    SELECT * FROM combination_total WHERE size > YOUR_SIZE ORDER BY size ASC LIMIT 2;
    

    我拥有的新脚本与此类似,但是它只是生成所有组合的数组,没有任何重复.似乎又很快了.注意$maxLength变量,当前设置为2000,可以使用您自己的最大大小进行修改.

    <?PHP
    $partLengths = array(150, 180, 270);
    $currentCombinations = array(
        array(
            'total' => 150,
            'combination' => array(150)
        ),
        array(
            'total' => 180,
            'combination' => array(180)
        ),
        array(
            'total' => 270,
            'combination' => array(270)
        )
    );
    $maxLength = 2000;
    $largestSize = 0;
    
    function generateCombination() {
        global $currentCombinations, $largestSize, $partLengths;
        $tmpCombinations = $currentCombinations;
        foreach ($tmpCombinations as $combination) {
            foreach ($partLengths as $partLength) {
                $newCombination = $combination['combination'];
                $newCombination[] = $partLength;
                sort($newCombination);
    
                $newCombinationTotal = array_sum($newCombination);
    
                if (!combinationExists($newCombination)) {
                    $currentCombinations[] = array(
                            'total' => $newCombinationTotal,
                            'combination' => $newCombination
                    );
                }
    
                $largestSize = ($newCombinationTotal > $largestSize) ? $newCombinationTotal : $largestSize;
            }
        }
    }
    
    function combinationExists($combination) {
        global $currentCombinations;
        foreach ($currentCombinations as $currentCombination) {
            if ($combination == $currentCombination['combination']) {
                return true;
            }
        }
        return false;
    }
    
    while ($largestSize < $maxLength) {
        generateCombination();
    }
    
    // here you can use $currentCombinations to generate sql/object/etc
    var_dump($currentCombinations);
    ?>
    

    python – 正则表达式,选择最接近的匹配

    python – 正则表达式,选择最接近的匹配

    假设以下单词序列
    BLA text text text  text text text BLA text text text text LOOK text text text BLA text text BLA

    我想要做的是将文本从BLA提取到LOOK,但是最接近外观的BLA.即我想得到

    BLA text text text text LOOK

    我应该如何使用正则表达式?我有一个有效的解决方案,但效率极低.

    BLA(?!.*?BLA.*?LOOK).*?LOOK

    是否有更好,更高效的方式来实现匹配这种模式?

    我想做的是:我希望与BLA相匹配,然后向前推进,直到用LOOK进行正向前瞻或用BLA进行负向前瞻.但我不知道如何把它变成正则表达式.

    作为引擎我在python中使用re.

    解决方法

    BLA(?:(?!BLA).)*?LOOK

    试试这个.看看演示.

    https://regex101.com/r/fA6wE2/12

    要么

    BLA(?:(?!BLA|LOOK).)*?LOOK

    为了更安全.

    关于如何在SQL Server 2005中选择最接近的匹配项?sql查询最接近的数字的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于php – 在十进制列中查找MySQL中最接近的匹配项、PHP-MYSQL与多个WHERE最接近的匹配项、php-从数组值组合计算最接近的匹配项、python – 正则表达式,选择最接近的匹配等相关知识的信息别忘了在本站进行查找喔。

    想了解SQL Server 2008 R2:匹配字符串的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于sql语句匹配字符串的相关问题,此外,我们还将为您介绍关于27.sqlserver2005连接字符串--2013-06-08、asp+SqlServer2008 开发【第一集:安装 SqlServer2008 以及登陆】、php5.2.3连接sqlserver2008,sqlserver2008、SQL Server2005与SQLServer2008并存时, 怎样连接到2008的新知识。

    本文目录一览:

    SQL Server 2008 R2:匹配字符串(sql语句匹配字符串)

    SQL Server 2008 R2:匹配字符串(sql语句匹配字符串)

    我有下表:

    表:

    CREATE TABLE str_matching(    colstr varchar(200));

    插入数据:

    INSERT INTO str_matching VALUES(''5sXYZA1010B'')INSERT INTO str_matching VALUES(''A1010B'')INSERT INTO str_matching VALUES(''AMZ103B15K'')INSERT INTO str_matching VALUES(''B15K'')INSERT INTO str_matching VALUES(''XC101'')INSERT INTO str_matching VALUES(''C101'')INSERT INTO str_matching VALUES(''502KMD1FZ10009L'')INSERT INTO str_matching VALUES(''FZ10009L'')INSERT INTO str_matching VALUES(''A9L'')INSERT INTO str_matching VALUES(''XZ049L'')INSERT INTO str_matching VALUES(''LM101'')

    预期的输出:我只想显示那些具有重复条目的记录,如果一个字符串与任何字符串的最后一部分匹配,那么我正在考虑将其作为重复。

    例如:我有两个字符串

    1. 5sXYZA1010B
    2. A1010B

    第二个字符串与第一个字符串的末尾匹配,因此要显示此类记录。

    注意 :字符串的长度不是固定的,可以随时匹配。

    预期结果:

    colstr              --------------------5sXYZA1010B         A1010B              AMZ103B15K          B15K                XC101               C101                502KMD1FZ10009L     FZ10009L

    答案1

    这应该做到(演示)

    SELECT DISTINCT CA.colstrFROM   str_matching s1       JOIN str_matching s2         ON s1.colstr <> s2.colstr            AND s2.colstr LIKE ''%'' + s1.colstr       CROSS APPLY (VALUES(s1.colstr),                          (s2.colstr)) CA(colstr)

    但是,如果str_matching有很多行,性能将会很差。在字符串的反面添加索引可以大大改善-如下例所示。

    CREATE TABLE str_matching(    colstr varchar(200),    colstr_rev AS REVERSE(colstr));CREATE INDEX ix_colstr_rev on str_matching(colstr_rev)SELECT colstr = REVERSE(CA.colstr_rev)FROM   str_matching s1       JOIN str_matching s2         ON s1.colstr_rev <> s2.colstr_rev            AND s2.colstr_rev LIKE  s1.colstr_rev + ''%''        CROSS APPLY (VALUES(s1.colstr_rev),                          (s2.colstr_rev)) CA(colstr_rev) GROUP BY CA.colstr_rev

    27.sqlserver2005连接字符串--2013-06-08

    27.sqlserver2005连接字符串--2013-06-08

    习惯用OLEDB+连接字符串去连数据库了,之前连sqlserver2000一直正常,因为换了个Y400的本本,装了win7,然后顺便sqlserver也搞了个64位的2005的。问题出现了,之前的数据库都连不上了。开始找了好久没找到原因,后来发现2005中uid跟pwd替换了之前的user跟password。顺便整理下连接字符串如下。

    转帖的一些文章整理下,原文链接在文中。

     SQL Native Client ODBC Driver
     
    标准安全连接 
       
    Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
     
    您是否在使用SQL Server 2005 Express? 请在“Server”选项使用连接表达式“主机名称/SQLEXPRESS”。 
      
    受信的连接
       
    Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;
     
    "Integrated Security=SSPI" 与 "Trusted_Connection=yes" 是相同的。
      
    连接到一个SQL Server实例
    指定服务器实例的表达式和其他SQL Server的连接字符串相同。  
    Driver={SQL Native Client};Server=myServerName/theInstanceName;Database=myDataBase;Trusted_Connection=yes;
     
       
    指定用户名和密码
    oConn.Properties("Prompt") = adPromptAlways
    Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;
     
       
    使用MARS (multiple active result sets)
       
    Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;MARS_Connection=yes;
     
    "MultipleActiveResultSets=true"与MARS_Connection=yes"是相同的。
    使用ADO.NET 2.0作为MARS的模块。 MARS不支持ADO.NET 1.0和ADO.NET 1.1。
      
    验证网络数据
       
    Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;Encrypt=yes;
     
       
    使用附加本地数据库文件的方式连接到本地SQL Server Express实例
       
    Driver={SQL Native Client};Server=./SQLExpress;AttachDbFilename=c:/asd/qwe/mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
     
    为何要使用Database参数?如果同名的数据库已经被附加,那么SQL Server将不会重新附加。 
      
    使用附加本地数据文件夹中的数据库文件的方式连接到本地SQL Server Express实例
       
    Driver={SQL Native Client};Server=./SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
     
    为何要使用Database参数?如果同名的数据库已经被附加,那么SQL Server将不会重新附加。
      
    数据库镜像
    Data Source=myServerAddress;Failover Partner=myMirrorServer;Initial Catalog=myDataBase;Integrated Security=True;
     
     
      
    SQL Native Client OLE DB Provider
     
    标准连接
       
    Provider=SQLNCLI;Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
     
    您是否在使用SQL Server 2005 Express? 请在“Server”选项使用连接表达式“主机名称/SQLEXPRESS”。 
      
    受信的连接
       
    Provider=SQLNCLI;Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;
     
    "Integrated Security=SSPI"与"Trusted_Connection=yes"相同
      
    连接到SQL Server实例
    指定服务器实例的表达式和其他SQL Server的连接字符串相同。  
    Provider=SQLNCLI;Server=myServerName/theInstanceName;Database=myDataBase;Trusted_Connection=yes;
     
       
    使用帐号和密码
    oConn.Properties("Prompt") = adPromptAlways
    oConn.Open "Provider=SQLNCLI;Server=myServerAddress;DataBase=myDataBase;
     
       
    使用MARS (multiple active result sets)
       
    Provider=SQLNCLI;Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;MarsConn=yes;
     
    "MultipleActiveResultSets=true"和"MARS_Connection=yes"是相同的。
    使用ADO.NET 2.0作为MARS的模块。 MARS不支持ADO.NET 1.0和ADO.NET 1.1。
      
    验证网络数据
       
    Provider=SQLNCLI;Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;Encrypt=yes;
     
       
    使用附加本地数据库文件的方式连接到本地SQL Server Express实例
       
    Provider=SQLNCLI;Server=./SQLExpress;AttachDbFilename=c:/asd/qwe/mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
     
    为何要使用Database参数?如果同名的数据库已经被附加,那么SQL Server将不会重新附加。
      
    使用附加本地数据文件夹中的数据库文件的方式连接到本地SQL Server Express实例
       
    Provider=SQLNCLI;Server=./SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
     
    为何要使用Database参数?如果同名的数据库已经被附加,那么SQL Server将不会重新附加。
      
    数据库镜像
    Data Source=myServerAddress;Failover Partner=myMirrorServer;Initial Catalog=myDataBase;Integrated Security=True;
     
     
      
    SqlConnection (.NET)
     
    标准连接
       
    Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
     
    使用serverName/instanceName作为数据源可以指定SQL Server实例。
    您是否在使用SQL Server 2005 Express? 请在“Server”选项使用连接表达式“主机名称/SQLEXPRESS”。 
      
    Standard Security alternative syntax
    Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;
     
       
    受信任的连接
       
    Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;
     
       
    Trusted Connection alternative syntax
    Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
     
       
    连接到一个SQL Server的实例
    指定服务器实例的表达式和其他SQL Server的连接字符串相同。  
    Server=myServerName/theInstanceName;Database=myDataBase;Trusted_Connection=True;
     
       
    来自WinCE设备的安全连接
    Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;User ID=myDomain/myUsername;Password=myPassword;
     
    仅能用于CE设备。
      
    带有IP地址的连接
       
    Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword; 
     
    使用MARS (multiple active result sets)
       
    Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;MultipleActiveResultSets=true;
     
    使用ADO.NET 2.0作为MARS的模块。 MARS不支持ADO.NET 1.0和ADO.NET 1.1。
      
    使用附加本地数据库文件的方式连接到本地SQL Server Express实例
       
    Server=./SQLExpress;AttachDbFilename=c:/asd/qwe/mydbfile.mdf;Database=dbname;Trusted_Connection=Yes;
     
    为何要使用Database参数?如果同名的数据库已经被附加,那么SQL Server将不会重新附加。
      
    使用附加本地数据文件夹中的数据库文件的方式连接到本地SQL Server Express实例
       
    Server=./SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
     
    为何要使用Database参数?如果同名的数据库已经被附加,那么SQL Server将不会重新附加。
      
    使用在SQL Server Express实例上的用户实例
    Data Source=./SQLExpress;Integrated Security=true;AttachDbFilename=|DataDirectory|/mydb.mdf;User Instance=true;
     
    数据库镜像
    Data Source=myServerAddress;Failover Partner=myMirrorServer;Initial Catalog=myDataBase;Integrated Security=True;
     
    Asynchronous processing
    Server=myServerAddress;Database=myDataBase;Integrated Security=True;Asynchronous Processing=True;
     

    本文来自CSDN博客,转载请标明出处: http://blog.csdn.net/jyh_jack/archive/2008/04/07/2257512.aspx 
     
    Sql Server2005连接字符串总结

    SqlConnection (.NET)

           标准安全连接

    以下是语法格式:
    Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

    使用"服务器名/实例名"的格式作为Data Source来连接到一个Sql Server服务器上的一个实例。

    你用过sql server 2005 Express么?不要忘记服务器的语法“Servername/SQLEXPRESS”(你要把Servername替换为装有sql server 2005 Express的计算机的名字)

         标准连接的另一种语法

    这个连接字符串和前一个的作用是一样的,只所以放到这里是为了说明有些连接参数带有相同的效果。


    以下是语法格式:
    Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;

        信任的连接


    以下是语法格式:
    Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;

           信任连接的另一种语法

    这个连接字符串和前一个的作用是一样的,只所以放到这里是为了说明有些连接参数带有相同的效果。


    以下是语法格式:
    Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;

        连接到数据库实例

    这个指名Sql Server 实例的语法中的server参数的值对所有连接Sql Server的字符串相同。

    以下是语法格式:
    Server=myServerName/theInstanceName;Database=myDataBase;Trusted_Connection=True;

         信任连接来至CE设备

    通常CE设备是没有验证和登陆到域的。用SSPI或信任验证的连接要使用下面的连接字符串。

    以下是语法格式:
    Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;User ID=myDomain/myUsername;Password=myPassword;

    注意:上面的语法只能用在CE设置上。

        通过IP地址的连接

    以下是语法格式:
    Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;

    DBMSSOCN=TCP/IP.这是指明使用IP地址而不是命名管道来连接。Data Source的最后是端口。1433是数据库的默认端口。

       允许多个结果集(Enable Mars (multiple active result sets))


    以下是语法格式:
    Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;MultipleActiveResultSets=true;

    此功能只支持Ado.net 2.0.

       在一个到本地SQL Server Express 实例的连接上附加数据库文件


    以下是语法格式:
    Server=./SQLExpress;AttachDbFilename=c:/asd/qwe/mydbfile.mdf;Database=dbname;Trusted_Connection=Yes;

    为什么要带上Database参数呢?因为如果有同名的数据库已经被附加上啦,SQL Server将不会重新附加该数据库。他将使用原数据库作为要连接的对象。

       在一个到本地SQL Server Express 实例的连接上附加数据库文件(数据文件在数据目录中。)


    以下是语法格式:
    Server=./SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;

    为什么要带上Database参数呢?因为如果有同名的数据库已经被附加上啦,SQL Server将不会重新附加该数据库。他将使用原数据库作为要连接的对象。

       使用本机上的SQL Server Express 实例上的用户实例。

    用户实例的连接创建了一个新的SQL Server 实例。此连接只能是在本地SQL Server 2005实例上并且是通过命名管的windows验证连接才有效。目的就是为了给用户创建一个完全权限的Sql Server 实例和有限的计算机管理员权限。


    以下是语法格式:
    Data Source=./SQLExpress;Integrated Security=true;AttachDbFilename=|DataDirectory|/mydb.mdf;User Instance=true;

    要使用User Instance 功能,你要在sql server服务器上启用他。你可以通过执行“sp_configure ''user instances enabled'', ''1''”来启用,执行“sp_configure ''user instances enabled'', ''0''”来禁用。

        数据库镜像

    如果你用Ado.Net或着SQL Native Client 连接到一个镜像的数据库,当一个数据库镜像出错时,你的应用程序应该提供自动切换连接的功能。那么,你应该在连接字符串中指明原始数据库名和镜像数据库名。


    以下是语法格式:
    Data Source=myServerAddress;Failover Partner=myMirrorServer;Initial Catalog=myDataBase;Integrated Security=True;

    当然还有很多连接数据库镜像的连接字符串的写法。这只是一个例子指明 failover功能。你还可以指明其他的连接字符串属性参数。

        异步处理

    SQL Server 2005允许通过Ado.net对象进行异步请求任务。


    以下是语法格式:
    Server=myServerAddress;Database=myDataBase;Integrated Security=True;Asynchronous Processing=True;

     

     

    SQL Server 2005 specials

     

       Context连接

    Connecting to "self" from within your CLR stored prodedure/function. The context connection lets you execute Transact-SQL statements in the same context (connection) that your code was invoked in the first place.


    以下是语法格式:
    C#
    using(SqlConnection connection = new SqlConnection("context connection=true"))
    {
          connection.Open();
          // Use the connection
    }

    ======================================================================

    转载声明:本文转自http://hi.baidu.com/shangfei2009/blog/item/c1bbae3c901de7e73d6d97bc.html

    在此谨对原创作者和转载分享网友,致以深深的谢意,也愿更多的网友能够分享和学习经典资料,谢谢!

    ===================================================
    Web.Config文件中SQLServerExpress数据库连接配置解释

    对于SQLServerExpress数据库连接配置,以前看到过几次,都是匆匆扫一眼,今天上午在一开源软件中又看到了它,感觉有必要对它有一个清楚的认识,示例如下:
    <add name="LocalSqlServer" connectionString="Data Source=./SQLExpress;Integrated Security=True;AttachDBFilename=|DataDirectory|TimeTracker.mdf;User Instance=true" />
    SqlConnectionStringBuilder实例化时,要用到 connectionString,如:SqlConnectionStringBuild builder = new SqlConnectionStringBuild(connectionString)。

       一、Data Source
    SqlConnectionStringBuilder 的DataSource属性,对应connectionString中的Data Source,“Data Source”可以由下列字符串代替:“server”,“address”,“addr”和“network address”。
    Data Source=./SQLExpress也可以写成这样Data Source=(local)/SQLExpress。

       二、Integrated Security
    SqlConnectionStringBuilder 的IntegratedSecurity属性,对应connectionString中的Integrated Security,“Integrated Security”可以写成“trusted_connection”,为true时,使用当前的 Windows 帐户凭据进行身份验证,为false时,需要在连接中指定用户 ID 和密码。

       三、AttachDBFilename
    SqlConnectionStringBuilder 的AttachDBFilename属性,对应connectionString中的 AttachDBFilename,“AttachDBFilename”可以写成“extended properties”,“initial file name”。AttachDbFileName属性指定连接打开的时候动态附加到服务器上的数据库文件的位置。这个属性可以接受数据库的完整路径和相对路 径(例如使用|DataDirectory|语法),在运行时这个路径会被应用程序的App_Data目录所代替。
    有一篇文章,专门解释DataDirectory是什么。

       四、User Instance
    SqlConnectionStringBuilder 的UserInstance属性,对应connectionString中的User Instance ,该值指示是否将连接从默认的 SQL Server Express 实例重定向到在调用方帐户之下运行并且在运行时启动的实例。UserInstance=true,在这种情况下,SQLServerExpress为了把 数据库附加到新的实例,建立一个新的进程,在打开连接的用户身份下运行。在ASP.NET应用程序中,这个用户是本地的ASPNET帐号或默认的 NetworkService,这依赖于操作系统。为了安全地附加非系统管理员帐号(例如ASP.NET帐号)提供的数据库文件,建立一个独立的 SQLServer用户实例是必要的。


    附 录:

    DataDirectory是什么?

    asp.net  2.0有一个特殊目录app_data,通常Sql  server  2005  express数据文件就放在这个目录,相应的数据库连接串就是:
    connectionString="……  data  source=./SQLEXPRESS;Integrated  Security=SSPI;AttachDBFilename=|DataDirectory|data.mdf;User  Instance=true"
    这里有一个DataDirectory的宏,它表示什么意义呢?

    DataDirectory是表示数据库路径的替换字符串。由于无需对完整路径进行硬编码,DataDirectory  简化了项目的共享和应用程序的部署。例如,无需使用以下连接字符串: 
    "Data  Source=  c:/program  files/MyApp/app_data/Mydb.mdf" 
    通过使用|DataDirectory|(包含在如下所示的竖线中),即可具有以下连接字符串: 
    "Data  Source  =  |DataDirectory|/Mydb.mdf" 。

    不仅仅是Sql server 2005 express中使用,也可以在其它的文件数据库中使用,例如Sqllite数据库文件的连接字符串:

    <add  name="DefaultDB" 
    connectionString="DriverClass=NHibernate.Driver.SQLite20Driver;Dialect=NHibernate.Dialect.SQLiteDialect;Data  Source=|DataDirectory|/data.db3" />

     

    2.连接数据库服务器

    <!--连接数据库服务器-->
      <add key="CRMonnection" value="Data Source=Sufei;Initial Catalog=CRM;Integrated Security=false;uid=1233;Password=123456"></add>

    一般是这样写的,意思 我就不在多说了大家一看就知道了。

    3.怎么样取呢来看个例子吧

    先看下面的代码

     


    <appSettings>
        
    <!--连接数据库服务器-->
            
    <add key="CRMonnection" value="Data Source=Sufei;Initial Catalog=CRM;Integrated Security=false;uid=nouter;Password=123456"></add>
            
    <add key="ForumName" value="漯河移动"/>
        
    <!--连接数据库文件-->
        
    <add key ="CRMConnectionString" value ="Data Source=./SQLEXPRESS;AttachDbFilename=|DataDirectory|CRM.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"/>
        
    </appSettings>

    取的方法在这里

     System.Configuration.ConfigurationSettings.AppSettings["CRMConnectionString"];

    asp+SqlServer2008 开发【第一集:安装 SqlServer2008 以及登陆】

    asp+SqlServer2008 开发【第一集:安装 SqlServer2008 以及登陆】

    参考:https://blog.csdn.net/i_likechard/article/details/75299983

    1,安装 sqlServer2008 的具体步骤参考网上其他教程,自己根据注释引导也能完成安装,同时注意在安装的时候需要勾选安装全部组件,毕竟不知道什么组件是需要还是不需要。

      在是否使用 sql server 登陆的选项,我建议勾选,并键入密码。!!!!6-1cxz

    2,安装的过程会很久,我差点以为卡死就重启了。

    3,在 win 菜单中找到下图第一个按钮,就打开客户端连接界面。

    4,如何登陆:浪费了我一些时间。必须使用以下图片的登陆方式。

      

      刚开始我也不知道服务器名称选什么,于是:

        

      但是没有注意到服务器类型发生了改变:

        

      登陆进去以后:

        

    这是一种错误的登陆,为什么不知道,以后再研究。

      正确的方式登陆后:

      

    这样才能创建数据库。

    php5.2.3连接sqlserver2008,sqlserver2008

    php5.2.3连接sqlserver2008,sqlserver2008

    php5.2.3连接sqlserver2008,sqlserver2008

    1,下载驱动 

    下载地址:https://www.microsoft.com/en-us/download/details.aspx?id=20098

    我下载的是:SQLSRV20.EXE ,因为我的php版本是5.2.3。具体的版本可以看下载说明。

    2,解压SQLSRV20.EXE,

    3,修改php.ini,添加 extension=php_sqlsrv_52_ts_vc6.dll

    立即学习“PHP免费学习笔记(深入)”;

    4,拷贝 extension=php_sqlsrv_52_ts_vc6.dll

    5,重启服务器

    $server = ''(local)'';
    $user = ''sa'';
    $pass=''sa'';
    $dbname=''testdb'';
    if(sqlsrv_connect($server, array(''UID'' => $user ,''PWD''=> $pass, ''Database'' => $dbname)))
    {
        echo "成功";
    }
    else
    {
        echo "失败";
    }
    ?>

     

    SQL Server2005与SQLServer2008并存时, 怎样连接到2008

    SQL Server2005与SQLServer2008并存时, 怎样连接到2008

    启动2008, 但是连接中却显示的是sql server 9.0, 这里是因为没有连接好. Server name: 对应的下拉列表中, 拉到最底下, Browse for more, / Local Servers / 数据库引擎 下面就有你本机上所有的实例名.。 选择 计算机名\SQL2008 , 就可以连接到了。 注: 200

    启动2008, 但是连接中却显示的是sql server 9.0, 这里是因为没有连接好.

    Server name: 对应的下拉列表中, 拉到最底下, "Browse for more", / "Local Servers" / "数据库引擎" 下面就有你本机上所有的实例名.。

    选择 计算机名\SQL2008 , 就可以连接到了。

    注: 2008连接之后, 连接中应该显示 SQL Server 10.0

    关于SQL Server 2008 R2:匹配字符串sql语句匹配字符串的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于27.sqlserver2005连接字符串--2013-06-08、asp+SqlServer2008 开发【第一集:安装 SqlServer2008 以及登陆】、php5.2.3连接sqlserver2008,sqlserver2008、SQL Server2005与SQLServer2008并存时, 怎样连接到2008的相关知识,请在本站寻找。

    本文标签:

    上一篇T-SQL CASE子句:关于使用外部JOIN指定WHEN NULL的问题

    下一篇SQL Server带有不可打印字符的排序顺序(sql语句不支持数据排序)