我的表在sql server上看起来像这样
void gener_random(int size, int **values) {
// Dereference the pointer to the pointer, to work
// on the variable declared in `main()' (the original pointer)
*values = malloc(size * sizeof(values));
if (*values == NULL) // Perhaps reutnr `int' and error code
return;
for(int i = 0; i < size; i++)
(*values)[i] = rand();
}
WordId和word正在与存储过程一起传递,如果wordId已经存在于表中,我需要检查我的存储过程,并且只有当wordId不存在时我才需要执行插入声明。
答案 0 :(得分:1)
首先,在wordid
上创建一个唯一索引:
create unique index unq_t_wordid on t(wordid);
这将保护数据并确保不会插入重复数据。
其次,在任何特定的insert
中,您可以在插入时进行检查:
insert into t (wordid, word)
select wordid, word
from (. . .) x
where not exists (select 1 from t where t.wordid = x.wordid);
当然,最终,我建议您将wordid
定义为标识列,但实际插入该值可能还有其他原因。
答案 1 :(得分:1)
试试这个:
CREATE PROCEDURE Your_ProcName(@wordId INT,@word VARCHAR(20))
AS
BEGIN
IF NOT EXISTS(SELECT 1 FROM Your_Table WHERE wordId = @wordId)
BEGIN
INSERT INTO Your_Table (wordid, word)
SELECT @wordId, @word
END
ELSE
BEGIN
PRINT 'Values already Exists'
END
END
答案 2 :(得分:0)
CREATE PROCEDURE Your_ProcName(@wordId INT,@word VARCHAR(20))
AS
BEGIN
Declare @nCount int;
SET NOCOUNT ON
Select @nCount = Count(*) from Your_Table WHERE wordId = @wordId
BEGIN TRY
DECLARE @ErrorMessage1 varchar(4000)
IF (@numRec > 0)
BEGIN
SET @ErrorMessage1 = 'ERROR: A wordId is already exists.'
RAISERROR (@ErrorMessage1, 16, 1)
END
IF @numRec = 0
BEGIN TRANSACTION
INSERT INTO Your_Table (wordid, word)
SELECT @wordId, @word
COMMIT
END TRY
BEGIN CATCH
SELECT
@ErrorMessage1 AS 'ERROR_MESSAGE'
RAISERROR (@ErrorMessage1, 16, 1)
END CATCH
END
GO